【发布时间】:2016-12-03 21:42:28
【问题描述】:
我正在尝试使用 Python 构建一个字符识别程序。我坚持对轮廓进行分类。我使用this page 作为参考。
我设法使用以下代码找到了轮廓:
mo_image = di_image.copy()
contour0 = cv2.findContours(mo_image.copy(),cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
contours = [cv2.approxPolyDP(cnt,3,True) for cnt in contour0[0]]
并使用这部分代码添加边界矩形并分割图像:
maxArea = 0
rect=[]
for ctr in contours:
maxArea = max(maxArea,cv2.contourArea(ctr))
if img == "Food.jpg":
areaRatio = 0.05
elif img == "Plate.jpg":
areaRatio = 0.5
for ctr in contours:
if cv2.contourArea(ctr) > maxArea * areaRatio:
rect.append(cv2.boundingRect(cv2.approxPolyDP(ctr,1,True)))
symbols=[]
for i in rect:
x = i[0]
y = i[1]
w = i[2]
h = i[3]
p1 = (x,y)
p2 = (x+w,y+h)
cv2.rectangle(mo_image,p1,p2,255,2)
image = cv2.resize(mo_image[y:y+h,x:x+w],(32,32))
symbols.append(image.reshape(1024,).astype("uint8"))
testset_data = np.array(symbols)
cv2.imshow("segmented",mo_image)
plt.subplot(2,3,6)
plt.title("Segmented")
plt.imshow(mo_image,'gray')
plt.xticks([]),plt.yticks([]);
但是,生成的片段似乎是随机顺序的。 这是原始图像,然后是带有检测到片段的处理图像。
然后程序分别输出每个段,但是它的顺序是:4 1 9 8 7 5 3 2 0 6 而不是0 1 2 3 4 5 6 7 8 9。
只需在“rect”中添加排序操作即可解决此问题,但相同的解决方案不适用于多行文档。
所以我的问题是:如何从左到右和从上到下对轮廓进行排序?
【问题讨论】:
-
您能添加一个
rect的内容示例吗? -
rect 包含 (x,y,w,h) 的每个检测到的轮廓 [(287, 117, 13, 46), (102, 117, 34, 47), (513, 116, 36 , 49), (454, 116, 32, 49), (395, 116, 28, 48), (334, 116, 31, 49), (168, 116, 26, 49), (43, 116, 30 , 48), (224, 115, 33, 50), (211, 33, 34, 47), (45, 33, 13, 46), (514, 32, 32, 49), (455, 32, 31 , 49), (396, 32, 29, 48), (275, 32, 28, 48), (156, 3 2, 26, 49), (91, 32, 30, 48), (333, 31, 33, 50)] 这是针对上述示例的。 (0-9)
-
@ZdaR 我先问了。另一个是重复的。
-
好的,我明白了,但是您可以从该问题中获取一些建议来解决您的问题。
标签: python