使用Python中的OpenCV进行盒子检测

问题描述

我正在尝试使用Python中的OpenCv检测图像中的框。我已经尽力尝试可以在网上找到的所有内容,但是我无法避免两次检测到每个框(请参见附图)

这是我正在使用的代码:

import numpy as np
import matplotlib.pyplot as plt
import cv2
img = cv2.imread('img5.jpg')
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(7,7),1)
edges = cv2.Canny(blur,50,50)

edges = 255-edges

kernel = np.ones((15,15),np.uint8)
#thresh = cv2.morphologyEx(edges,cv2.MORPH_OPEN,kernel)
erosion = cv2.erode(edges,kernel,iterations = 2)
dilation = cv2.dilate(erosion,iterations = 2)

contours,hierarchy = cv2.findContours(dilation,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)

boxes = []
minArea=200 
for cnt in contours:
    area=cv2.contourArea(cnt) 
    if area>minArea:
        x,y,w,h = cv2.boundingRect(cnt)  
        cv2.rectangle(img,(x,y),(x + w - 1,y + h - 1),255,2)
        boxes.append(cv2.boundingRect(cnt))       
plt.imsave('result.jpg',img)

Original image

Results

有人可以帮忙吗?预先感谢!

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)