Skip to content

Instantly share code, notes, and snippets.

@carlosdelfino
Last active June 26, 2024 14:57

Revisions

  1. carlosdelfino revised this gist Jun 26, 2024. 1 changed file with 19 additions and 2 deletions.
    21 changes: 19 additions & 2 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -1,10 +1,27 @@
    # Instalar o QT, o Lib OpenCV e o Poppler
    # Passos Detalhados para Instalação no Windows

    ## Instalar Poppler para Windows:

    * Baixe o Poppler de aqui: http://blog.alivate.com.au/poppler-windows/.
    * Extraia o conteúdo do arquivo ZIP baixado.
    * Adicione o caminho do binário do Poppler (path\to\poppler\bin) à variável de ambiente PATH.
    * Instalar Pacotes Python Necessários:

    Use pip para instalar os pacotes necessários. Vamos instalar opencv-python-headless para evitar problemas relacionados ao Qt, e outras bibliotecas necessárias.

    ```
    pip install opencv-python-headless numpy pdf2image pillow matplotlib
    ```

    # Passos para Instalação no Windows

    ## Instalar o QT, o Lib OpenCV e o Poppler

    ```
    sudo apt-get install qt5-default libopencv-dev poppler-utils
    ```

    # Instalar o OpenCV NumPY PDF2Image Pillow e MatPlotLib no Python 3
    ## Instalar o OpenCV NumPY PDF2Image Pillow e MatPlotLib no Python 3

    ```
    pip install opencv-python-headless numpy pdf2image pillow matplotlib
  2. carlosdelfino created this gist Jun 26, 2024.
    19 changes: 19 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,19 @@
    # Instalar o QT, o Lib OpenCV e o Poppler

    ```
    sudo apt-get install qt5-default libopencv-dev poppler-utils
    ```

    # Instalar o OpenCV NumPY PDF2Image Pillow e MatPlotLib no Python 3

    ```
    pip install opencv-python-headless numpy pdf2image pillow matplotlib
    ```



    # Como usar

    Após instalar as bibliotecas acima, ir no diretório onde está o PDF com o esquemático ou as imagens em PNG ou JPG, executar o script python `pdfpngjpgextrator.py` seguido do nome do arquivo e se for PDF com a chave de comando --page para dizer em qual página está o esquema, se não for informado ele vai precorura na primeira página.

    Nessa versão ele apenas traça as linhas sobre o esquemático, melhorias futuras um dia virão.
    109 changes: 109 additions & 0 deletions pdfpngjpgextrator.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,109 @@
    import cv2
    import numpy as np
    from pdf2image import convert_from_path
    from PIL import Image
    import matplotlib.pyplot as plt
    import argparse
    import os

    # Função para converter PDF em imagem
    def pdf_to_images(pdf_path, page_number=None):
    if page_number is not None:
    images = convert_from_path(pdf_path, first_page=page_number, last_page=page_number)
    else:
    images = convert_from_path(pdf_path)
    return images

    # Função para carregar imagem (PNG, JPG)
    def load_image(image_path):
    image = cv2.imread(image_path)
    return image

    # Função para detectar vértices e arestas
    def detect_vertices_and_edges(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    contours, _ = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

    vertices = []
    for contour in contours:
    approx = cv2.approxPolyDP(contour, 0.02 * cv2.arcLength(contour, True), True)
    vertices.append(approx)
    cv2.drawContours(image, [approx], 0, (0, 255, 0), 2) # Desenhar contornos na imagem

    return vertices, edges

    # Função para desenhar áreas delimitadas
    def draw_delimited_areas(image):
    def draw_rectangle(event, x, y, flags, param):
    global ix, iy, drawing, img

    if event == cv2.EVENT_LBUTTONDOWN:
    drawing = True
    ix, iy = x, y

    elif event == cv2.EVENT_MOUSEMOVE:
    if drawing:
    img_copy = img.copy()
    cv2.rectangle(img_copy, (ix, iy), (x, y), (0, 255, 0), 2)
    cv2.imshow('image', img_copy)

    elif event == cv2.EVENT_LBUTTONUP:
    drawing = False
    cv2.rectangle(img, (ix, iy), (x, y), (0, 255, 0), 2)

    global img, ix, iy, drawing
    drawing = False
    img = image.copy()

    cv2.namedWindow('image')
    cv2.setMouseCallback('image', draw_rectangle)

    while True:
    cv2.imshow('image', img)
    if cv2.waitKey(1) & 0xFF == 27:
    break

    cv2.destroyAllWindows()
    return img

    # Função principal
    def main(file_path, page_number):
    if not os.path.exists(file_path):
    print(f"O arquivo {file_path} não existe.")
    return

    file_ext = os.path.splitext(file_path)[1].lower()

    if file_ext == '.pdf':
    if page_number is not None:
    images = pdf_to_images(file_path, page_number)
    else:
    images = pdf_to_images(file_path)
    page_number = 1
    for i, image in enumerate(images):
    image_array = np.array(image)
    vertices, edges = detect_vertices_and_edges(image_array)
    plt.imshow(cv2.cvtColor(image_array, cv2.COLOR_BGR2RGB))
    plt.title(f'Página {page_number}')
    plt.show()
    page_number += 1
    break
    elif file_ext in ['.png', '.jpg', '.jpeg']:
    image = load_image(file_path)
    vertices, edges = detect_vertices_and_edges(image)
    plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
    plt.show()

    delimited_image = draw_delimited_areas(image)
    plt.imshow(cv2.cvtColor(delimited_image, cv2.COLOR_BGR2RGB))
    plt.show()
    else:
    print(f"Formato de arquivo {file_ext} não suportado.")

    if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Processar arquivos de imagens de circuitos eletrônicos.')
    parser.add_argument('file_path', type=str, help='Caminho do arquivo a ser processado (PDF, PNG, JPG)')
    parser.add_argument('--page', type=int, default=None, help='Número da página do PDF a ser processada (se aplicável)')
    args = parser.parse_args()
    main(args.file_path, args.page)