Trying to segment characters and save it in order to image files. But contours are being drawn in a different order?

风格不统一 提交于 2019-12-04 20:38:01

You can try to find the location of letter by using the center of contours.

M = cv2.moments(contours)
cX = int(M["m10"] / M["m00"])
cY = int(M["m01"] / M["m00"])

Then you can find the order of characters with using cX and cY (If only one line, you use only cX)

This code sorts the bounding boxes and achieves what was probably intended, does it?

import cv2
strFormula="1!((x+1)*(x+2))" # '!' means a character is not allowed in file name
img = cv2.imread("test26.png")
imgGray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
ret, imgThresh = cv2.threshold(imgGray, 127, 255, 0)

(major_ver, minor_ver, subminor_ver) = (cv2.__version__).split('.')
if int(major_ver)  < 3 :
    contours , hierarchy  = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
else :
    image, contours , _   = cv2.findContours(imgThresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
#:if

lstBoundingBoxes = []
for cnt in contours:  lstBoundingBoxes.append(cv2.boundingRect(cnt))
lstBoundingBoxes.sort()

charNo=0
for item in lstBoundingBoxes[1:]: # skip first element ('bounding box' == entire image)
    charNo += 1
    fName = "charAtPosNo-" + str(charNo).zfill(2) + "_is_[ " + strFormula[charNo-1] + " ]"+ ".png"; 
    x,y,w,h = item
    cv2.imwrite(fName, img[y:y+h, x:x+w])
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!