Home > Enterprise >  How do I detect only the black rectangle that appears in the reference image with OpenCV
How do I detect only the black rectangle that appears in the reference image with OpenCV

Time:12-01

Original Image

I need to detect only the black rectangle that appears there, but for some reason my code does not detect it but it does detect many other things.

import cv2

img=cv2.imread('vision.png') #read image
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Blur=cv2.GaussianBlur(gray,(5,5),1) #apply blur to roi
Canny=cv2.Canny(Blur,10,50) #apply canny to roi

#Find my contours
contours =cv2.findContours(Canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)[0]

cntrRect = []
for i in contours:
        epsilon = 0.05*cv2.arcLength(i,True)
        approx = cv2.approxPolyDP(i,epsilon,True)
        if len(approx) == 4:
            cv2.drawContours(img,cntrRect,-1,(0,255,0),2)
            cv2.imshow('Image Rect ONLY',img)
            cntrRect.append(approx)

cv2.waitKey(0)
cv2.destroyAllWindows()

How do I detect only the black rectangle that appears in the image

enter image description here

But this code detect more rectangles and I don't want whis, but I only want detect the black countour rectangle enter image description here

CodePudding user response:

Here is one way to do that in Python/OpenCV.

Threshold the image. Then use morphology to fill out the rectangle. Then get the largest contour and draw on the input.

Input:

enter image description here

import cv2
import numpy as np

# load image
img = cv2.imread("black_rectangle_outline.png")

# convert to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# threshold
thresh = cv2.threshold(gray, 30, 255, cv2.THRESH_BINARY)[1]

# apply close morphology
kernel = np.ones((111,111), np.uint8)
morph = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)

# invert so rectangle is white
morph = 255 - morph

# get largest contour and draw on copy of input
result = img.copy()
contours = cv2.findContours(morph, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
big_contour = max(contours, key=cv2.contourArea)
cv2.drawContours(result, [big_contour], 0, (255,255,255), 1)

# write result to disk
cv2.imwrite("black_rectangle_outline_thresh.png", thresh)
cv2.imwrite("black_rectangle_outline_morph.png", morph)
cv2.imwrite("black_rectangle_outline_result.png", result)

# display results
cv2.imshow("THRESH", thresh)
cv2.imshow("MORPH", morph)
cv2.imshow("RESULT", result)
cv2.waitKey(0)
cv2.destroyAllWindows()

Threshold Image:

enter image description here

Morphology Image:

enter image description here

Result:

enter image description here

  • Related