核桃派2B:opencv python的 Canny findContours得到两个非常接近的轮廓,角点有几个像素的差距,如何处理?
kernel_2 = cv2.getStructuringElement(cv2.MORPH_RECT,(3, 3))
eroded = cv2.erode(img_gray_binary,kernel_2,iterations=2)# 【0330new】 iterations=2 #腐蚀图像
dilated = cv2.dilate(eroded,kernel_2) #膨胀图像
img_cannyedges = cv2.Canny(dilated,100,200)
contours, hierarchy = cv2.findContours(img_cannyedges, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
序号140面积符合
bounding_rect: (286, 229, 127, 146)
x, y, w, h: 286 229 127 146
轮廓角点数量和数据: 3 [[[288 229]] [[412 300]] [[295 374]]]
序号141面积符合
bounding_rect: (286, 229, 127, 146)
x, y, w, h: 286 229 127 146
轮廓角点数量和数据: 4 [[[288 229]] [[290 358]] [[296 374]] [[412 300]]]
**********************************
序号67面积符合
bounding_rect: (286, 230, 126, 144)
x, y, w, h: 286 230 126 144
轮廓角点数量和数据: 4 [[[288 230]] [[411 300]] [[296 373]] [[291 372]]]
序号69面积符合
bounding_rect: (286, 230, 126, 144)
x, y, w, h: 286 230 126 144
轮廓角点数量和数据: 4 [[[288 230]] [[291 372]] [[297 373]] [[411 299]]]
调整代码再次测试,涛声依旧。
'''
实验名称:轮廓检测
实验平台:核桃派
'''
import cv2
import numpy as np
cam = cv2.VideoCapture(1) # 打开摄像头,确认好编号
while (cam.isOpened()): # 确认被打开
retval, img = cam.read() # 从摄像头中实时读取图像
cv2.imshow('color', img) #显示图像
break
#将彩色图像转化为灰度图像(单通道)
imgcolor=img.copy()
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', img) #显示图像
#将灰度图像转化二值图像
t,img = cv2.threshold(img, 127, 255, cv2.THRESH_BINARY_INV)
cv2.imshow('binary', img) #显示图像
#第2组阈值边缘检测
img = cv2.Canny(img, 200, 400)
cv2.imshow('e2img', img) #显示原图像
#检测轮廓
contours, hierarchy = cv2.findContours(img, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
print('轮廓数量:',len(contours))
#在原图img0上描绘轮廓,绿色
#img = cv2.drawContours(imgcolor, contours, -1, (0,255,0), 2)
#cv2.imshow('contours', img) #显示图像
data_con=[]
for index,contour in enumerate(contours):
area = cv2.contourArea(contour)
#if area < 5000 or 100000 < area:
# continue
# print(f'序号{index}面积{area}符合')
#print(f'序号{index}')
if 2000>area>1500:
print(f'序号{index}面积{area}符合')
x, y, w, h = cv2.boundingRect(contour)
print('x, y, w, h:',x, y, w, h)
data_con.append(contour)
print('data_con=',len(data_con))
for i in data_con:
img = cv2.drawContours(imgcolor, i, -1, (0,255,0), 2)
cv2.imshow('contours', img) #显示图像
cv2.imshow('contours', img) #显示图像
print('waint...')
cv2.waitKey() #等待键盘任意按键按下
cv2.destroyAllWindows() #关闭窗口
轮廓数量: 325
序号77面积1740.0符合
x, y, w, h: 459 332 83 39#**********************
序号78面积1740.0符合
x, y, w, h: 459 332 83 39#**********************
序号179面积1919.0符合
x, y, w, h: 126 212 57 65#--------------------------
序号181面积1939.5符合
x, y, w, h: 126 212 57 65#--------------------------
序号204面积1802.0符合
x, y, w, h: 278 192 55 65#++++++++++++++++
序号208面积1821.5符合
x, y, w, h: 278 192 55 65#++++++++++++++++
data_con= 6
waint...
为何有重复数据?
修改一下参数,终于没有刚才的现象了:
contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
参考链接:用实际例子详细探究OpenCV的轮廓检测函数findContours(),彻底搞清每个参数、每种模式的真正作用与含义-CSDN博客
更为奇怪的是,linux下thonny的imshow窗体,点击窗体上的保存按钮,点击后一个画面一闪而过,然后窗体就没有反应了。只能停止运行。(仍未解决)