灰度变换
下列式子为原来,s代表新灰度,r代表原灰度。
函数变换实现代码
def linear_chg(self, img_data): # 线性变换
"""
:param img_data
:return:new_img_data
"""
print("变换规则为y=kx+b\n默认k=1,b=0,如需调整,请修改linear_chg函数中k,b对应的值")
k = 1.05
b = 0
new_img_data = img_data
shape = img_data.shape
for i in range(shape[0]):
for j in range(shape[1]):
new_img_data[i, j] = k * img_data[i, j] + b
# if new_img_data[i, j] >= 256:
# new_img_data[i, j] = 255
# if new_img_data[i, j] < 0:
# new_img_data[i, j] = 0
# 图像显示的时候会自动处理,下面函数中都不再做处理
return new_img_data
def pow_chg(self, img_data): # 幂次变换
'''
:param img_data:
:return: a new im object
'''
print("变换规则为s=c(r+e)^y\n,c默认值为1,e默认值为0,y默认值为1,如需修改,请在pow_chg函数中对应参数修改")
c = 1
e = 0
y = 1.05
new_img_data = img_data
shape = img_data.shape
for i in range(shape[0]):
for j in range(shape[1]):
new_img_data[i, j] = c * pow((img_data[i, j] + e), y)
return new_img_data
def lg_chg(self, img_data): # 对数变换
'''
:param img_data:
:return:
'''
new_img_data = img_data
shape = img_data.shape
print("变换规则为s=clog(r+1),c默认值为1")
c = 1
for i in range(shape[0]):
for j in range(shape[1]):
new_img_data[i, j] = c * math.log(img_data[i, j] + 1)
return new_img_data
def oppo_chg(self, img_data): # 反相
L = 256
new_img_data = img_data
shape = img_data.shape
for i in range(shape[0]):
for j in range(shape[1]):
new_img_data[i, j] = L - 1 - img_data[i, j]
return new_img_data
阈值处理
s=L-1,r>T
s=0,r<=T
实现代码
def thre_proce(self, img_data, T=192): # 阈值处理
'''
:param img_data: img_data array
:param T:
:return: a new_img_data array
'''
new_img_data = img_data
shape = img_data.shape
for i in range(shape[0]):
for j in range(shape[1]):
if img_data[i, j] >= T:
new_img_data[i, j] = 255
if img_data[i, j] < T:
new_img_data[i, j] = 0
return new_img_data
直方图均衡化
实现代码
def img_data_equal(self, img_data): # 直方图均衡化
L = 256
new_img_data = img_data
num_count = [0] * L
num_per = [0] * L
total_per = [0] * 256
pixels = []
new = [0] * L
im_shape = img_data.shape
for i in range(im_shape[0]):
for j in range(im_shape[1]):
pixels.append(img_data[i, j])
total = len(pixels)
result = Counter(pixels)
for i in range(L):
num_count[i] = result[i]
num_per[i] = num_count[i] / total
total_per[i] = total_per[i - 1] + num_per[i]
for i in range(L):
new[i] = int((L - 1) * total_per[i] + 0.5)
for i in range(im_shape[0]):
for j in range(im_shape[1]):
new_img_data[i, j] = new[img_data[i, j]]
return new_img_data
源文件下载地址http://www.toseek.cc/py/2.py
see you next!