Arjun
Arjun

Reputation: 49

How to ignore a image region for contour detection, OpenCV

--Original images for reference--- enter image description hereoriginal image for reference enter image description here Original Image

Hello OpenCV pro users!

I am working on a use case to detect rectangle contours and extract them for analysis in these kind of images

I want to ignore these 1 region (marked in yellow) in the image as it's not needed, how to ignore this region while using the contour detection?

Any tips will be helpful, thanks in advance.. :)

enter image description here

def getContours(img_name, img, img_color):
    
    FLAG = 200
    _, contours, hierachy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    has_Mask =False
    has_hori_mask = False
    has_vertical_mask = False
    
    coordinates_dict = {}
    
    for cnt in contours:
        area = cv2.contourArea(cnt)
        if area > 1000:
            #cv2.drawContours(imgContour, cnt, -1, (0,0,255), 3)
            peri = cv2.arcLength(cnt, True)
            approx = cv2.approxPolyDP(cnt, 0.02*peri,True)
            if len(approx)==4: # only interested in squares/rectangles
                has_Mask = True
                objCorner = 4
                x, y, w, h = cv2.boundingRect(approx)
                if h>150 and w<40:
                    has_vertical_mask = True
                    cv2.rectangle(img_color, (x,y), (x+w, y+h), (0,0,255), 3)
                    coordinates_dict["vertical"]=y+h
                elif w>150 and h<24:
                    has_hori_mask = True
                    cv2.rectangle(img_color, (x,y), (x+w, y+h), (0,255,0), 3)
                    coordinates_dict["horizontal"]=y+h

    # save the image
    cv2.imwrite(os.path.join(validation_folder, img_name), img_color)

enter image description here

Upvotes: 2

Views: 1216

Answers (1)

T A
T A

Reputation: 1756

As your images always have the same margin at the top, you can just exclude this image region in the detection process:

# margin in pixels
top_margin = 85

src = cv2.imread('test.jpg')
src_cropped = src[top_margin:src.shape[0], :]
src_gray = cv2.cvtColor(src_cropped, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(src_gray, 127, 255, cv2.THRESH_BINARY_INV)
im2, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(src_cropped, contours, -1, (0,0,255), 3)

You can then apply this to the original image to get your bounding boxes in the cropped area for the whole image:

src[top_margin:src.shape[0], :] = src_cropped

You get the following result when drawing all contours:

enter image description here

If you apply this together with your constraints, it should eliminate the unwanted contour in the top.

Upvotes: 1

Related Questions