简体   繁体   中英

unable to get contour properly

I am playing with openCV and doing simple below task.

1) Read Image

2) thresholding

3) Finding contours.

4) Drawing all contours in the blank image.

5) Drawing individual contour.

Drawing all contours on the dummy image looks good, whereas drawing single contour produces scattered contour as shown in the below images.

Original:

在此处输入图像描述

All Contours:

在此处输入图像描述

Single Contour:

在此处输入图像描述

Please find the code below.

import  cv2
import numpy as np

#Reading Image.
srcImg = cv2.imread("./bottle.jpeg")

#Color Conversion.

grayedImg = cv2.cvtColor(srcImg,cv2.COLOR_RGB2GRAY)
__, thresholdedImg = cv2.threshold(grayedImg, 240, 255, cv2.THRESH_BINARY)

#Noice Removal
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3,3))
erodeImage = cv2.erode(thresholdedImg,kernel, iterations=1)
dilatedImg = cv2.dilate(erodeImage,kernel, iterations=1)
_, contours, _ = cv2.findContours(dilatedImg,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

#draw All Contours.

dummyImg = np.zeros(grayedImg.shape, dtype=grayedImg.dtype)
cv2.drawContours(dummyImg, contours, -1, 255, 1)
cv2.imshow("All Contours", dummyImg)
cv2.imwrite("allContours.jpeg",dummyImg)

#draw Individual Contours.

mask =  np.zeros(dummyImg.shape[:2], dtype= dummyImg.dtype)
isolatedImg = cv2.drawContours(mask, contours[9], -1, 255, 1)

cv2.imshow("Indivial Contours.", isolatedImg)
cv2.imwrite("single.jpeg",isolatedImg)

cv2.waitKey(0)

You have to enclose another set of square brackets:

isolatedImg = cv2.drawContours(mask, [contours[9]], -1, 255, 1)

Expected result:

在此处输入图像描述

If you dig deep, cv2.findContours() returns a list of arrays. Now each array contains details on the number of points making up the contour.

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