Как восстановить поврежденный текст в изображении - PullRequest
1 голос
/ 13 июня 2019

У меня есть изображение, на котором мне нужно исправить его яркость и контрастность, а код должен быть динамическим, чтобы в будущем, если я получу новые изображения, я мог легко запустить тот же код для коррекции яркости и контрастности, не внося изменений в код.

Мне удалось правильно скорректировать яркость и контраст изображения.

import cv2
import numpy as np
import glob,os,sys
from PIL import Image, ImageEnhance 

class ImageEnhancement:  

    def readImages(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 processImages(imageFiles):
        for imagePath in imageFiles:
            img_name = os.path.splitext(os.path.basename(imagePath))[0]
            new_folder = sys.argv[2]+'/'+img_name+'/'
            os.makedirs(new_folder, exist_ok=True)

            src_img = cv2.imread(imagePath)


            #Create the identity filter, but with the 1 shifted to the right!
            kernel = np.zeros( (9,9), np.float32)
            kernel[4,4] = 2.0   #Identity, times two! 

            #Create a box filter:
            boxFilter = np.ones( (9,9), np.float32) / 81.0

            #Subtract the two:
            kernel = kernel - boxFilter

            #Note that we are subject to overflow and underflow here...but I believe that
            # filter2D clips top and bottom ranges on the output, plus you'd need a
            # very bright or very dark pixel surrounded by the opposite type.

            custom = cv2.filter2D(src_img, -1, kernel)

            img_hsv = cv2.cvtColor(custom, cv2.COLOR_BGR2HSV)
            img_hsv[:,:,2] = [[max(pixel - 25, 0) if pixel < 190 else min(pixel + 25, 255) for pixel in row] for row in img_hsv[:,:,2]]

            #cv2.imwrite(new_folder+'/'+img_name+'.png',cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR))

            grayscaled = cv2.cvtColor(cv2.cvtColor(img_hsv, cv2.COLOR_HSV2BGR),cv2.COLOR_BGR2GRAY)
            retval, threshold = cv2.threshold(grayscaled, 200, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)

            #k = np.array([[1, 1, 1], [1, 1, 1], [1, 1, 1]], np.uint8)
            #closing = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, k)
            #cv2.imshow("closing", closing)
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            #k1 = np.ones((3, 3), np.uint8)
            #erosion = cv2.erode(threshold, k1, iterations = 1)
            #cv2.imshow("erosion", erosion)
            #cv2.waitKey(0)
            #cv2.destroyAllWindows()

            #contour,_= cv2.findContours(threshold, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
            #cv2.drawContours(threshold,contour, -1, 0,0)

            #kernel = np.zeros((2,1),np.uint8)
            #dilation = cv2.dilate(threshold,kernel,iterations=1)

            #kernel = np.zeros((3,3),np.uint8)
            #erosion = cv2.erode(threshold,kernel,iteration=1)
            #dilation = cv2.morphologyEx(threshold, cv2.MORPH_CLOSE, kernel)

            cv2.imwrite(new_folder+'/'+img_name+'.png',threshold)



imageFiles = ImageEnhancement.readImages(sys.argv[1])
ImageEnhancement.processImages(imageFiles)

В выходном изображении исправлены яркость и контрастность, но возникает новая проблема, когда несколько символов повреждены (доступны только половинные символы). Мне нужна помощь для того же, чтобы я мог получить полные символы в изображении.

Входное изображение

Input_Image

Вывод с поврежденными символами

Output_Image_With_Damaged_Character

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...