opencv学习(python)-对比度增强
下面的程序都是我在学习opencv算法精解基于python与C++一书参考后自己又打了一遍。
构建灰度直方图
import numpy as np
import cv2
import matplotlib.pyplot as plt
def calcGrayHist(image):
rows=image.shape[0]
cols=image.shape[1]
print(rows,cols)
grayHist =np.zeros([256],np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[image[r][c]] +=1
return grayHist
if __name__ =="__main__":
image=cv2.imread("E:\PyCharmproject\Opencvdemo\Tranforms.png",cv2.IMREAD_ANYCOLOR)
grayHist=calcGrayHist(image)
x_range=range(256)
plt.plot(x_range,grayHist,'r',linewidth=2,c='black')
y_maxValue=np.max(grayHist)
plt.axis([0,255,0,y_maxValue])
plt.xlabel('gray Level')
plt.ylabel("number of pixels")
plt.show()
直方图正规化
import cv2
import numpy as np
import sys
if __name__ =="__main__":
i=cv2.imread("Tranforms.png")
imax=np.max(i)
imin=np.min(i)
omin,omax=0,255
a=float((omax-omin)/(imax-imin))
b=float(omin-(omax-omin)/(imax-imin)*imin)
o=a*i+b
o=o.astype(np.uint8) #转换类型
cv2.imshow("i",i)
cv2.imshow("o",o)
cv2.waitKey(0)
cv2.destroyAllWindows()
伽马变换
import cv2
import numpy as np
import sys
if __name__ =="__main__":
i=cv2.imread("Tranforms.png")
fi=i/255.0
o=np.power(fi,0.4)
# o=o.astype(np.uint8)
cv2.imshow("fi",fi)
# cv2.imshow("i",i)
cv2.imshow("o",o)
cv2.waitKey(0)
cv2.destroyAllWindows()
全局直方图均衡化
import numpy as np
import cv2
import matplotlib.pyplot as plt
import math
def calcGrayHist(image):
rows=image.shape[0]
cols=image.shape[1]
grayHist =np.zeros([256],np.uint64)
for r in range(rows):
for c in range(cols):
grayHist[image[r][c]] +=1
return grayHist
def equalHist(image):
rows=image.shape[0]
cols=image.shape[1]
grayHist=calcGrayHist(image)
#计算累加灰度直方图
zeroCumuMoment=np.zeros([256],np.uint32)
for p in range(256):
if p==0:
zeroCumuMoment[p]=grayHist[0]
else:
zeroCumuMoment[p]=zeroCumuMoment[p-1]+grayHist[p]
out=np.zeros([256],np.uint8)
conf=256.0/(rows*cols)
for p in range(256):
q= conf*float(zeroCumuMoment[p])-1
if q >=0:
out[p]=math.floor(q)
else:
out[p]=0
equalhistimage=np.zeros(image.shape,np.uint8)
for r in range(rows):
for c in range(cols):
equalhistimage[r][c]=out[image[r][c]]
return equalhistimage
if __name__ =="__main__":
image=cv2.imread("Tranforms.png")
equalhistimage=equalHist(image)
cv2.imshow("equalhistimage",equalhistimage)
cv2.imshow("image",image)
cv2.waitKey(0)
cv2.destroyAllWindows()
未完待续…