简体   繁体   中英

Detect objects that are located on the side of an image opencv

I am trying to detect several objects in an image; however, some objects are located at the edge, so not all contours are shown in the image. How can we detect objects that are "cropped" in a way? Can we enclose the contours at the edges of an image?

First, I blurred the image, applied a canny detector, dilated, and then eroded the edges.
Here is my code:

img = cv2.imread('porosity1.png')

img1 = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

blur = cv2.GaussianBlur(gray, (7,7),0)

med = np.median(blur)

lower = int(max(0,0.7*med))

upper = int(min(255,1.3*med))

edged = cv2.Canny(blur, lower, upper)

edged = cv2.dilate(edged, None, iterations=1)
edged = cv2.erode(edged, None, iterations=1)

This is what I get for edge detection, which is fine with me.

enter image description here

But when I want to fill my contours to check if the detector was able to detect all objects (even the ones at the side of the image) I get this:

gray, cnts, hierarchy = cv2.findContours(edged, mode = cv2.RETR_CCOMP,method = cv2.CHAIN_APPROX_NONE )

cnts1 = []

external_contours = np.zeros(gray.shape)

for i,cnt in enumerate(cnts):
    
    
    #External contours
    if cv2.contourArea(cnt)>100.0: #To exclude small contour areas
        cv2.drawContours(external_contours, cnts, i, 1, -1)
        cnts1.append(cnt)
        
        
        #Last column in each row in the hierarchy

plt.imshow(external_contours, cmap='gray')

enter image description here

The reason I want to detect is that I want to find the enclosed area of the objects.

You can use cv2.convexHull function on the found contours, then the contours on the edges will be closed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM