猿问

如何使用Python OpenCV裁剪图像上的每个字符?

我生成了像这样的OpenCV图像

从最后一行代码中,如何分别裁剪和显示当前图像中的每个字符?


法典


    labels = measure.label(thresh, connectivity=2, background=0)

    charCandidates = np.zeros(thresh.shape, dtype="uint8")


    for label in np.unique(labels):


        if label == 0:

            continue


        labelMask = np.zeros(thresh.shape, dtype="uint8")

        labelMask[labels == label] = 255

        cnts = cv2.findContours(labelMask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

        cnts = imutils.grab_contours(cnts)


        if len(cnts) > 0:

            c = max(cnts, key=cv2.contourArea)

            (boxX, boxY, boxW, boxH) = cv2.boundingRect(c)


            aspectRatio = boxW / float(boxH)

            solidity = cv2.contourArea(c) / float(boxW * boxH)

            heightRatio = boxH / float(crop_frame.shape[0])


            keepAspectRatio = aspectRatio < 1.0

            keepSolidity = solidity > 0.15

            keepHeight = heightRatio > 0.4 and heightRatio < 0.95



        if keepAspectRatio and keepSolidity and keepHeight:

            hull = cv2.convexHull(c)

            cv2.drawContours(charCandidates, [hull], -1, 255, -1)


    charCandidates = segmentation.clear_border(charCandidates)

    cnts = cv2.findContours(charCandidates.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    cnts = imutils.grab_contours(cnts)

    cv2.imshow("Original Candidates", charCandidates)


    thresh = cv2.bitwise_and(thresh, thresh, mask=charCandidates)

    cv2.imshow("Char Threshold", thresh)

谢谢。


Qyouu
浏览 198回答 1
1回答

汪汪一只猫

这是一个简单的方法:转换为灰度大津的门槛查找等值线,从左到右对等值线进行排序,并使用等值线区域进行过滤提取投资回报率在 Otsu 的阈值化以获得二进制图像之后,我们使用&nbsp;imutils.contours.sort_contours()&nbsp;从左到右对轮廓进行排序。这可确保当我们循环访问每个轮廓时,每个字符的顺序都正确。此外,我们使用最小阈值区域进行滤波,以消除小噪声。这是检测到的字符我们可以使用Numpy切片提取每个字符。以下是每个已保存角色的投资回报率import cv2from imutils import contours# Load image, grayscale, Otsu's thresholdimage = cv2.imread('1.png')gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)thresh = cv2.threshold(gray,0,255,cv2.THRESH_OTSU + cv2.THRESH_BINARY)[1]# Find contours, sort from left-to-right, then cropcnts = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)cnts = cnts[0] if len(cnts) == 2 else cnts[1]cnts, _ = contours.sort_contours(cnts, method="left-to-right")ROI_number = 0for c in cnts:&nbsp; &nbsp; area = cv2.contourArea(c)&nbsp; &nbsp; if area > 10:&nbsp; &nbsp; &nbsp; &nbsp; x,y,w,h = cv2.boundingRect(c)&nbsp; &nbsp; &nbsp; &nbsp; ROI = 255 - image[y:y+h, x:x+w]&nbsp; &nbsp; &nbsp; &nbsp; cv2.imwrite('ROI_{}.png'.format(ROI_number), ROI)&nbsp; &nbsp; &nbsp; &nbsp; cv2.rectangle(image, (x, y), (x + w, y + h), (36,255,12), 2)&nbsp; &nbsp; &nbsp; &nbsp; ROI_number += 1cv2.imshow('thresh', thresh)cv2.imshow('image', image)cv2.waitKey()
随时随地看视频慕课网APP

相关分类

Python
我要回答