python-opencv-使图⽚更清晰的⼏种⽅法所有代码已测试通过。
import cv2
import numpy as np
def gamma(source,out):
img = cv2.imread(source, cv2.IMREAD_GRAYSCALE)
# 归1
Cimg = img /255
# 伽玛变换
gamma =0.7
O = np.power(Cimg, gamma)
O = O *255
# 效果
cv2.imwrite(out, O,[int(cv2.IMWRITE_PNG_COMPRESSION),0])
def hist(source):
img = cv2.imread(source, cv2.IMREAD_GRAYSCALE)
# 求出img 的最⼤最⼩值
Maximg = np.max(img)
Minimg = np.min(img)
# 输出最⼩灰度级和最⼤灰度级
Omin, Omax =0,255
# 求 a, b
a =float(Omax - Omin)/(Maximg - Minimg)
b = Omin - a * Minimg
# 线性变换
O = a * img + b
对象图片高清O = O.astype(np.uint8)
cv2.imshow('enhance', O)
#cv2.imwrite('hist.png', O, [int(cv2.IMWRITE_PNG_COMPRESSION), 0])
cv2.waitKey(0)
cv2.destroyAllWindows()
def hist_auto(source):
img = cv2.imread(source,0)
img = size(img,None, fx=0.5, fy=0.5)
# 创建CLAHE对象
clahe = ateCLAHE(clipLimit=2.0, tileGridSize=(8,8))
# 限制对⽐度的⾃适应阈值均衡化
dst = clahe.apply(img)
# 使⽤全局直⽅图均衡化
equa = cv2.equalizeHist(img)
# 分别显⽰原图,CLAHE,HE
#cv.imshow("img", img)
#cv2.imshow("dst", dst)
cv2.imwrite('hist_auto.png', dst,[int(cv2.IMWRITE_PNG_COMPRESSION),0])
def calcGrayHist(I):
# 计算灰度直⽅图
h, w = I.shape[:2]
grayHist = np.zeros([256], np.uint64)
for i in range(h):
for j in range(w):
grayHist[I[i][j]]+=1
return grayHist
def equalHist(img):
import math
# 灰度图像矩阵的⾼、宽
h, w = img.shape
# 第⼀步:计算灰度直⽅图
grayHist = calcGrayHist(img)
grayHist = calcGrayHist(img)
# 第⼆步:计算累加灰度直⽅图
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]
# 第三步:根据累加灰度直⽅图得到输⼊灰度级和输出灰度级之间的映射关系 outPut_q = np.zeros([256], np.uint8)
cofficient =256.0/(h * w)
for p in range(256):
q = cofficient *float(zeroCumuMoment[p])-1
if q >=0:
outPut_q[p]= math.floor(q)
else:
outPut_q[p]=0
# 第四步:得到直⽅图均衡化后的图像
equalHistImage = np.zeros(img.shape, np.uint8)
for i in range(h):
for j in range(w):
equalHistImage[i][j]= outPut_q[img[i][j]]
return equalHistImage
def linear(source):
img = cv2.imread(source,0)
# 使⽤⾃⼰写的函数实现
equa = equalHist(img)
cv2.imshow("equa", equa)
cv2.imwrite('temp.png', equa,[int(cv2.IMWRITE_PNG_COMPRESSION),0]) cv2.waitKey()
source ="raw.jpg"
#gamma(source)
hist(source)
#hist_auto(source)
#linear(source)
#gamma('temp.png','g2.png')
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论