Home > OS >  Detect square symbols in a diagram image in python using OpenCV
Detect square symbols in a diagram image in python using OpenCV

Time:11-22

I am trying to detect the square shaped symbols in a P&ID (a diagram) image file using OpenCV. I tried following tutorials that use contours, but that method doesn't seem to work with such diagram images. Using Hough Lines I am able to mark the vertical edges of these squares, but I am not sure how to use these edges detect the squares. All squares in an image have the same dimensions, but the dimensions might not be same across different images, hence template matching didn't work for me.

My code using Hough Lines:

import cv2 as cv
import numpy as np
import math

img = cv.imread('test_img.jpg')
img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
img_display = img.copy()
ret,thresh = cv.threshold(img_gray,250,255,cv.THRESH_BINARY)
image_inverted = cv.bitwise_not(thresh)

linesP = cv.HoughLinesP(image_inverted, 1, np.pi / 1, 50, None, 50, 2)

if linesP is not None:
    for i in range(0, len(linesP)):
        l = linesP[i][0]
        length = math.sqrt((l[2] - l[0])**2   (l[3] - l[1])**2)
        if length < 100:
            cv.line(img_display, (l[0], l[1]), (l[2], l[3]), (0,0,255), 1, cv.LINE_AA)
            
cv.imwrite('img_display.png', img_display)

Input image:

input image

Output Image:

output image

In the above code, I've set it to detect only vertical lines because it wasn't detecting horizontal lines reliably.

CodePudding user response:

If you know that the lines are horizontal or vertical you can filter them out by combining erode and dilate (the enter image description here

  • Related