我正在尝试使用代码来增加灰度图像的对比度,使其更清晰。我似乎无法使此代码工作。我试图获得像素中每个值的分布频率(不使用除cv2之外的任何模块)并获得累积分布频率,然后我可以使用下面的等式更改该值。知道我的代码有什么问题吗?
import cv2
img=cv2.imread(raw_input())
shape=img.shape
row=shape[0]
col=shape[1]
def df(img): #to make a histogram (count distribution frequency)
values=[]
occurances=[]
for i in range (len(img)):
for j in img[i]:
values.append(j)
if j in values:
count +=3
occurances.append(count)
return occurances
def cdf (img): #cumulative distribution frequency
values2=[]
for i in values:
j=0
i=i+j
j+1
values2.append(i)
return values2
def h(img): #equation for the new value of each pixel
h=((cdf(img)-1)/((row*col)-1))*255
return h
newimage=cv2.imwrite('a.png')
提前谢谢。
答案 0 :(得分:1)
如果你不知道,opencv提供了一个用于历史分析均衡的内置函数,记录在案here。
还有关于您的代码:
分配频率(或直方图)计算不正确,因为您只计算图像中出现的颜色频率。您应该计算所有颜色值的外观,即使它们没有出现。 此外,每当您的颜色再次出现时,您都会在列表中添加该颜色的新元素,这没有多大意义。我不太确定+ = 3来自哪里。
我会做的是这样的事情:
def df(img): #to make a histogram (count distribution frequency)
values = [0] * 256
for i in range(len(img)):
for j in img[i]:
values[j] += 1
答案 1 :(得分:1)
这是一个有一些修改的解决方案。它提供以下输出
主要修改:
df()
和cdf()
功能变得简单。在执行时打印输出以检查它是否与您期望的输出匹配equalize_image()
函数通过从正常像素范围(range(0,256)
)插值到累积分布函数来均衡图像以下是代码:
import cv2
img = cv2.imread(raw_input('Please enter the name of your image:'),0) #The ',0' makes it read the image as a grayscale image
row, col = img.shape[:2]
def df(img): # to make a histogram (count distribution frequency)
values = [0]*256
for i in range(img.shape[0]):
for j in range(img.shape[1]):
values[img[i,j]]+=1
return values
def cdf(hist): # cumulative distribution frequency
cdf = [0] * len(hist) #len(hist) is 256
cdf[0] = hist[0]
for i in range(1, len(hist)):
cdf[i]= cdf[i-1]+hist[i]
# Now we normalize the histogram
cdf = [ele*255/cdf[-1] for ele in cdf] # What your function h was doing before
return cdf
def equalize_image(image):
my_cdf = cdf(df(img))
# use linear interpolation of cdf to find new pixel values. Scipy alternative exists
import numpy as np
image_equalized = np.interp(image, range(0,256), my_cdf)
return image_equalized
eq = equalize_image(img)
cv2.imwrite('equalized.png', eq)