如何从图像中删除边界

时间:2019-05-21 07:33:23

标签: python opencv image-processing contour bounding-box

我有一张Form60的图像,我需要从其中删除所有边界线,而又不影响框中的任何内容。

我能够删除大约70%的边界线,但是现在图像中的噪点太多了。

import cv2
import numpy as np
import os,glob,sys
import logging


class BorderManipulation:

    def readImage(inputFolder):
        ext = ['.png', '.jpg', '.gif', '.jpeg', '.tif', '.tiff']
        files = []
        path = inputFolder + "/*.*"
        files = glob.glob(path)
        imageFiles=[]
        for i in files:
                exten=os.path.splitext(i)[1]
                if exten in ext:
                        imageFiles.append(i)
        return imageFiles

    def processImage(imageFiles,output_dir):
        for imagePath in imageFiles:
            try:    
                img_name = os.path.splitext(os.path.basename(imagePath))[0]
                new_folder = output_dir
                os.makedirs(new_folder, exist_ok=True)

                src = cv2.imread(imagePath)
                grayimage = cv2.cvtColor(src,cv2.COLOR_BGR2GRAY)
                binaryimage = cv2.adaptiveThreshold(grayimage,250,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
                             cv2.THRESH_BINARY,115,2.3)
                #retval3,otcu = cv2.threshold(grayimg,125,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
                maxval, binary_inv_image = cv2.threshold(binaryimage, 150, 255, cv2.THRESH_BINARY_INV)

                horizontal = binary_inv_image.copy()
                vertical = binary_inv_image.copy()
                rows,cols = horizontal.shape

                #Specify size on horizontal & verticalsize axis
                horizontalsize = 45 #int(cols / 30)
                verticalsize = 45 #int(rows / 30)

                #Create structure element for extracting horizontal &verticalsize lines through morphology operations
                horizontalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (horizontalsize,1))
                horizontal = cv2.erode(horizontal, horizontalStructure, (-1, -1))
                horizontal = cv2.dilate(horizontal, horizontalStructure, (-1, -1))


                verticalStructure = cv2.getStructuringElement(cv2.MORPH_RECT, (1, verticalsize))
                vertical = cv2.erode(vertical, verticalStructure, (-1, -1))
                vertical = cv2.dilate(vertical, verticalStructure, (-1, -1))

                Contours,hierarchy= cv2.findContours(vertical.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
                for count,Contour in enumerate(Contours):
                    x,y,w,h = cv2.boundingRect(Contour)
                    if x == 2:
                        processingaImage = cv2.drawContours(vertical,[Contour],0,(0,0,250),2)
                        #print(processingaImage)


                combine= horizontal+vertical
                #cv2.imwrite(new_folder+'{}.png',combine)
                cleanImage = binary_inv_image - combine
                cv2.imwrite(os.path.join(new_folder,img_name+'.png'),cleanImage)

            except Exception as ex:
                print(ex)
                #logger.error(ex)
                #logging.error('This is an error message')
                logger.error(sys.exc_info())


logging.basicConfig(filename=sys.argv[2]+"_Error_Log.log",format='%(asctime)s %(message)s',filemode='w')   

logger=logging.getLogger()   

logger.setLevel(logging.DEBUG)              


try:            

    imageFiles = BorderManipulation.readImage(sys.argv[1])

except Exception as ex:

    logger.error(ex)

    print(ex)

finally:

    print("*********Process Completed***********") 

BorderManipulation.processImage(imageFiles,sys.argv[2])

我希望获得如何在不影响框内字段名称和内容的情况下将噪声降至最低的帮助。我已在下面链接了输入图像。

输入图像

Input Image

0 个答案:

没有答案