我一直在试图检测的复选框。虽然我能够检测在其他图像中的轮廓方形我是不是能够得到轮廓为这个特定的图像。请帮我检测的复选框。
输入图像:
这是我的代码
for myfile in files:
image=cv2.imread(myfile)
image = cv2.resize(image, (180,60), interpolation = cv2.INTER_AREA)
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
#apply otsu's threshold
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]
#setting up threshold values
threshold_max_area = 300
threshold_min_area = 10
#finding contours in the image
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
#getting the coordinates for each checkbox
count=0
centers=[]
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.035 * peri, True)
x,y,w,h = cv2.boundingRect(approx)
aspect_ratio = w / float(h)
area = cv2.contourArea(c)
if len(approx) == 4 and area < threshold_max_area and area > threshold_min_area and (aspect_ratio >= 0.9 and aspect_ratio <= 1.1):
centers.append([x,y,x+w,y+h])
count=count+1
print(centers)
cv2.imshow(" ",image)
cv2.waitKey()
最佳答案
这是解决它的一种方法。
步骤1:二值化
import os
import cv2
import numpy as np
import pandas as pd
### reading input image
image_path='test_sample.jpg'
image=cv2.imread(image_path)
### converting BGR to Grayscale
gray_scale=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
### Binarising image
th1,img_bin = cv2.threshold(gray_scale,180,225,cv2.THRESH_OTSU)
二进制图片:步骤2:寻找水平和垂直线
### defining kernels
lWidth = 2
lineMinWidth = 15
kernal1 = np.ones((lWidth,lWidth), np.uint8)
kernal1h = np.ones((1,lWidth), np.uint8)
kernal1v = np.ones((lWidth,1), np.uint8)
kernal6 = np.ones((lineMinWidth,lineMinWidth), np.uint8)
kernal6h = np.ones((1,lineMinWidth), np.uint8)
kernal6v = np.ones((lineMinWidth,1), np.uint8)
### finding horizontal lines
img_bin_h = cv2.morphologyEx(~img_bin, cv2.MORPH_CLOSE, kernal1h) # bridge small gap in horizonntal lines
img_bin_h = cv2.morphologyEx(img_bin_h, cv2.MORPH_OPEN, kernal6h) # kep ony horiz lines by eroding everything else in hor direction
水平线:## detect vert lines
img_bin_v = cv2.morphologyEx(~img_bin, cv2.MORPH_CLOSE, kernal1v) # bridge small gap in vert lines
img_bin_v = cv2.morphologyEx(img_bin_v, cv2.MORPH_OPEN, kernal6v)# kep ony vert lines by eroding everything else in vert direction
垂直线:步骤3:组合水平线和垂直线
def fix(img):
img[img>127]=255
img[img<127]=0
return img
img_bin_final = fix(fix(img_bin_h)|fix(img_bin_v))
组合二进制输出:步骤4:使用已连接的组件查找矩形
### getting labels
ret, labels, stats,centroids = cv2.connectedComponentsWithStats(~img_bin_final, connectivity=8, ltype=cv2.CV_32S)
### drawing recangles for visualisation
for x,y,w,h,area in stats[2:]:
cv2.rectangle(image,(x,y),(x+w,y+h),(0,0,255),2)
最终输出:关于python - 复选框检测opencv,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63084676/