我有一幅需要校正其亮度和对比度的图像,并且代码需要是动态的,以便将来在获得新图像时,我可以轻松地运行相同的代码来校正亮度和对比度,而无需对图像进行任何更改。代码。
我能够正确校正图像的亮度和对比度。
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)
在输出的图像中,亮度和对比度得到了校正,但是出现了一个新问题,即几乎没有字符被损坏(只有半个字符可用)。我希望获得相同的帮助,以便我可以在图像中获得完整的字符。
Output with damaged characters