python - 如何在图像中绘制多个最大的物体轮廓

标签 python opencv

我正在尝试提取图像中多个最大对象的轮廓。目前,我只能提取最大的对象之一,而其他对象则没有轮廓。这是我正在测试的阈值后的图像。

testing image
enter image description here

cntrs = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

cntrs = cntrs[0] if len(cntrs) == 2 else cntrs[1]
# create black background image
result = np.zeros_like(src)
area_thresh = 0
for c in cntrs:
    area = cv2.contourArea(src)
    if area > area_thresh:
        area_thresh = area
        big_contour = c

这是我当前使用的代码,仅提取一个对象。

最佳答案

试试这个:

import cv2

# Read the image
img=cv2.imread('test.jpg')

# Convert to Gray
imgGray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Apply threshold and Dilate (to bring out the lines of the plane)
ImgThresh = cv2.threshold(imgGray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
ImgThreshDilation = cv2.dilate(ImgThresh,(3,3),iterations = 2)

# Find edges
imgEdges = cv2.Canny(ImgThreshDilation,100,200)

# Find contour
contours,hierarchy =cv2.findContours(imgEdges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

# Loop through contours and find the two biggest area.
for cont in contours:
    area=cv2.contourArea(cont)
    if area>300:
        #print(area)
        cv2.drawContours(img,cont,-1,(0,0,255),2)

cv2.imshow('Image with planes in Red',img)


Final Result in red

这是上面代码的编辑。
import cv2

# Read the image
img=cv2.imread('test.jpg')
imgCont=img.copy()

# Convert to Gray
imgGray =255- cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

# Find edges
imgEdges = cv2.Canny(imgGray,150,200)

# Find contour
contours,hierarchy =cv2.findContours(imgEdges,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) 

# Loop through contours and find the two biggest area.
for cont in contours:
    area=cv2.contourArea(cont)
    if area>150:
        #print(area)
        cv2.drawContours(imgCont,cont,-1,(0,0,255),5)

# Save your pictures with the contour in red
cv2.imwrite('Image with planes in Red.jpg',imgCont)


结果:
Result for the second Code

关于python - 如何在图像中绘制多个最大的物体轮廓,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61450506/

相关文章:

python - 模板片段缓存似乎不适用于某些自定义模板标签

python - Rubik cubefinder.py 错误

image - 选择霍夫变换的参数

c++ - 使用OpenCV从2D图像点计算3D世界点

python - Opencv在Python中检测四边形

python - 无法从 csv 文件中获取前 N 个重复出现的值

python - 如何抓取 URL 中包含页码的多个页面

python - 如何对 Tornado 进行单元测试?

opencv - 使用关于opencv的realsense2将深度图像映射到彩色图像

python - 如何从图像中去除颜色