我正在尝试使用Python构建一个字符识别程序。我在对轮廓进行排序时遇到了困难。我正在使用这个页面作为参考。
我成功地使用以下代码找到了轮廓:
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
的示例内容吗? - Martin Evans