我要分割成单个字符图像的单词图像很少

时间:2019-05-28 06:25:45

标签: python opencv mask contour image-segmentation

我只有几个手写单词的图像,我想将它们分割成单个字符图像并分别保存这些图像。

我能够分割图像,但是很少有图像不能正确分割(某些数据丢失)

def imageSegmentation(fldr):
    for file in fldr:
        for f in os.listdir(file):
            im = cv2.imread(file + f)
            imgray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
            ret, thresh = cv2.threshold(imgray, 127, 255, 0)

            contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            con_img = cv2.drawContours(im, contours, -1, (0, 0, 0), 1)
            # cv2.imshow("Contour_Image",con_img)
            # cv2.waitKey(0)
            # cv2.destroyAllWindows()

            newfolder = file + "\\contour\\" + f + "\\"
            os.makedirs(newfolder, exist_ok=True)

            fname = os.path.splitext(f)[0]

            cv2.imwrite((newfolder + fname + ".png"), con_img)

            newfolder2 = file + "\\seg\\" + fname + "\\"
            os.makedirs(newfolder2, exist_ok=True)

            sorted_ctrs = sorted(contours, key=lambda cntr: cv2.boundingRect(cntr)[0])

            for i, cntr in enumerate(sorted_ctrs):
                # Get bounding box
                x, y, w, h = cv2.boundingRect(cntr)

                # Getting ROI
                roi = im[y:y + h, x:x + w]
                roi = ~roi

                if w > 4 and h > 15:
                    cv2.imwrite(newfolder2 + "{}.png".format(i), roi)
                    cv2.imshow("Segmented_Image", roi)
                    cv2.waitKey(0)
                    cv2.destroyAllWindows()

我希望图像中的所有字符单独保存,而不会丢失任何数据并尽可能减少噪音

我尝试分割的图像很少:-

  • 1: enter image description here
  • 2: enter image description here
  • 3: enter image description here
  • 4: enter image description here
  • 5: enter image description here
  • 6: enter image description here
  • 7: enter image description here
  • 8: enter image description here

0 个答案:

没有答案