python - 如何轮廓图像中的多个最大对象
问题描述
我正在尝试提取图像中多个最大对象的轮廓。目前我只能提取最大的对象之一,其他对象没有轮廓。这是阈值后的图像,我正在测试。
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
这是我目前使用的代码,它只提取一个对象。
解决方案
Try this:
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)
Here is an edit of the above code.
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)
推荐阅读
- marklogic - MLCP 内容转换和触发器可以在文档摄取期间一起使用吗?
- java - Android:如何让屏幕进入待机状态并保持接收BLE通知
- python - 工业 PIR 传感器始终为高
- android - 如何打开我的 android 应用程序以从 Google 助理(如 Whatsapp、Message 和 Telegram)发送消息?
- javascript - 提交表单时将 JavaScript 对象添加到表单数据
- python - 来自 3 列数据框的三角形热图
- mysql - sql select查询显示列标题而不是列中的数据
- javascript - HTML DIV 显示相同的输入
- java - tika:禁用查看 zip 文件
- r - 添加具有列名的新列