直方图均衡化
实现函数
def histogram(img):
if img.dtype == 'uint8':
hist = np.zeros(256)
l = 256
elif img.dtype == 'uint16':
hist = np.zeros(65536)
l = 65536
else:
return 0
for i in range(img.shape[0]):
for j in range(img.shape[1]):
hist[img[i][j]] += 1
return l, hist
实例
def histogram(img):
if img.dtype == 'uint8':
hist = np.zeros(256)
l = 256
elif img.dtype == 'uint16':
hist = np.zeros(65536)
l = 65536
else:
return 0
for i in range(img.shape[0]):
for j in range(img.shape[1]):
hist[img[i][j]] += 1
return l, hist
if __name__ == '__main__':
img=cv2.imread('../image/lena-gray.png',-1)
L,hist = histogram(img)
Cumulative_histogram = {}
tmp = 0
for i in range(hist.size):
if hist[i] != 0:
Cumulative_histogram[i] = hist[i]/img.size+tmp
tmp = Cumulative_histogram[i]
for i in Cumulative_histogram.keys():
tmp = math.floor((L-1) * Cumulative_histogram[i]+0.5)
Cumulative_histogram[i] = tmp
new_img = np.array(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i][j] in Cumulative_histogram.keys():
new_img[i][j] = Cumulative_histogram[img[i][j]]
l,new_hist = histogram(new_img)
x_ori = np.linspace(0,L,256)
x_new = np.linspace(0,l,256)
plt.subplot(231),plt.imshow(img,cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(232),plt.bar(x_ori,hist)
plt.title("histogram"),plt.xlabel("Bins")
plt.ylabel("# of Pixels"),plt.xlim([0,256])
plt.subplot(234),plt.imshow(new_img,cmap = 'gray')
plt.title('Processed Image'), plt.xticks([]), plt.yticks([])
plt.subplot(235),plt.bar(x_new,new_hist)
plt.title("histogram"),plt.xlabel("Bins")
plt.ylabel("# of Pixels"),plt.xlim([0,256])
plt.show()
直方图归并化
def histogram(img):
if img.dtype=='uint8':
hist = np.zeros(256)
l = 256
elif img.dtype=='uint16':
hist = np.zeros(65536)
l = 65536
else:
return 0
for i in range(img.shape[0]):
for j in range(img.shape[1]):
hist[img[i][j]]+=1
return l,hist
if __name__ == '__main__':
img = cv2.imread('../image/lena-gray.png',-1)
L,hist = histogram(img)
Cumulative_histogram = {}
tmp = 0
for i in range(hist.size):
if hist[i] != 0:
Cumulative_histogram[i] = hist[i]/img.size+tmp
tmp = Cumulative_histogram[i]
tmp = random.sample(range(0,255), 50)
keys = sorted(tmp)
values = [0]*50
tmp = 0
for i in range(49):
values[i] = 0.02*(i+1)
for i in Cumulative_histogram.keys():
tmp1 = Cumulative_histogram[i]
tmp = 1
for j in range(50):
if (abs(tmp1 - values[j]) < tmp):
Cumulative_histogram[i] = keys[j]
tmp = abs(tmp1 - values[j])
else:
break
new_img = np.array(img)
for i in range(img.shape[0]):
for j in range(img.shape[1]):
if img[i][j] in Cumulative_histogram.keys():
new_img[i][j] = Cumulative_histogram[img[i][j]]
l,new_hist = histogram(new_img)
x_ori = np.linspace(0,L,256)
x_new = np.linspace(0,l,256)
values = [0.02*512*512]*50
plt.subplot(231),plt.imshow(img,cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(232),plt.bar(x_ori,hist)
plt.title("histogram"),plt.xlabel("Bins")
plt.ylabel("# of Pixels"),plt.xlim([0,256])
plt.subplot(233),plt.bar(keys,values)
plt.title("regulation histogram"),plt.xlabel("Bins")
plt.ylabel("# of Pixels"),plt.xlim([0,256])
plt.subplot(234),plt.imshow(new_img,cmap = 'gray')
plt.title('Processed Image'), plt.xticks([]), plt.yticks([])
plt.subplot(235),plt.bar(x_new,new_hist)
plt.title("histogram"),plt.xlabel("Bins")
plt.ylabel("# of Pixels"),plt.xlim([0,256])
plt.show()
模拟卷积函数
def template_convolution(img,temp):
r,c = img.shape
h1,v1 = temp.shape
h = math.floor(h1 / 2)
v = math.floor(v1 / 2)
N = sum(sum(temp))
new_img = np.zeros((r,c))
for i in range(h,r-h):
for j in range(v,c-v):
if N !=0:
new_img[i][j] = abs(np.sum(img[i-h:i+h+1,j-v:j+v+1] * temp))/N
else:
new_img[i][j] = abs(np.sum(img[i-h:i+h+1,j-v:j+v+1] * temp))
return new_img
if __name__ == '__main__':
img = cv2.imread('../image/lena-gray.png', -1)
t_3 = np.ones((3,3))
t_11 = np.ones((11,11))
def template_sort(img,temp,flag=None):
r,c = img.shape
h = math.floor(temp/2)
new_img = np.zeros((r,c))
for i in range(h,r-h):
for j in range(h,c-h):
if flag == None:
new_img[i][j] = np.mean(img[i-h:i+h+1,j-h:j+h+1])
elif flag == 1:
new_img[i][j] = np.max(img[i-h:i+h+1,j-h:j+h+1])
elif flag == -1:
new_img[i][j] = np.min(img[i-h:i+h+1,j-h:j+h+1])
elif flag == 0:
new_img[i][j] = np.median(img[i-h:i+h+1,j-h:j+h+1])
return new_img
if __name__ == '__main__':
img = cv2.imread('lena-gray.png', -1)
new_img_mean = template_sort(img, 3)
new_img_max = template_sort(img, 3, 1)
new_img_min = template_sort(img, 3, -1)
new_img_median = template_sort(img, 3, 0)
plt.subplot(231),plt.imshow(img,cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(232),plt.imshow(new_img_mean,cmap = 'gray')
plt.title('3*3 mean'), plt.xticks([]), plt.yticks([])
plt.subplot(233),plt.imshow(new_img_max,cmap = 'gray')
plt.title('3*3 max'), plt.xticks([]), plt.yticks([])
plt.subplot(234),plt.imshow(new_img_min,cmap = 'gray')
plt.title('3*3 min'), plt.xticks([]), plt.yticks([])
plt.subplot(235),plt.imshow(new_img_median,cmap = 'gray')
plt.title('3*3 median'), plt.xticks([]), plt.yticks([])
plt.show()
傅里叶变换
import cv2
import numpy as np
from matplotlib import pyplot as plt
import math
import random
import datetime
import pywt
def DFT(sig):
N = sig.size
V = np.array([[np.exp(-1j*2*np.pi*v*y/N) for v in range(N)] for y in range(N)])
return sig.dot(V)
def FFT(x):
N = x.shape[1]
if N % 2 > 0:
raise ValueError("size of x must be a power of 2")
elif N <= 8:
return np.array([DFT(x[i,:]) for i in range(x.shape[0])])
else:
X_even = FFT(x[:,::2])
X_odd = FFT(x[:,1::2])
factor = np.array([np.exp(-2j * np.pi * np.arange(N/2) / N) for i in range(x.shape[0])])
return np.hstack([X_even + np.multiply(factor[:,:int(N/2)],X_odd),
X_even - np.multiply(factor[:,:int(N/2)],X_odd)])
def FFT2D(img):
return FFT(FFT(img).T).T
def FFT_SHIFT(img):
M,N = img.shape
M = int(M/2)
N = int(N/2)
return np.vstack((np.hstack((img[M:,N:],img[M:,:N])),np.hstack((img[:M,N:],img[:M,:N]))))
def forward_input_data(input_data, num):
j = num / 2
for i in range(1, num - 2):
if (i < j):
complex_tmp = input_data[i]
input_data[i] = input_data[int(j)]
input_data[int(j)] = complex_tmp
k = num / 2
while (j >= k):
j = j - k
k = k / 2
j = j + k
return input_data
def fft_1d(in_data, num):
PI = np.pi
in_data = forward_input_data(in_data,num)
M = 1
tmp = num / 2;
while (tmp != 1):
M = M + 1
tmp = tmp / 2
for L in range(1, M + 1):
B = int(math.pow(2, L - 1))
for J in range(0, B):
P = math.pow(2, M - L) * J
for K in range(J, num, int(math.pow(2, L))):
complex_ret = complex(math.cos((2 * PI / num) * P),math.sin((2 * PI / num) * P))
complex_mul = complex_ret*in_data[K + B]
complex_add = in_data[K]+complex_mul
complex_sub = in_data[K]-complex_mul
in_data[K] = complex_add
in_data[K + B] = complex_sub
return in_data
if __name__ == '__main__':
img = cv2.imread('../image/lena-gray.png', -1)
m,n = img.shape
start = datetime.datetime.now()
my_fft = (FFT2D(img))
end = datetime.datetime.now()
print("the time spent of method1:", end - start)
my_fft = abs(FFT_SHIFT(my_fft))
method1_spectrum = 20 * np.log(np.abs(my_fft))
start = datetime.datetime.now()
fft_result = np.zeros(img.shape, dtype=np.complex)
for i in range(m):
fft_result[i] = fft_1d(img[i, :].astype(np.complex), n)
for i in range(n):
fft_result[:, i] = fft_1d(fft_result[:, i], m)
end = datetime.datetime.now()
print("the time spent of method2:", end - start)
fshift = np.fft.fftshift(fft_result)
method2_spectrum = 20 * np.log(np.abs(fshift))
start = datetime.datetime.now()
f = np.fft.fft2(img)
end = datetime.datetime.now()
print("the time spent of np-fft:", end - start)
fshift = np.fft.fftshift(f)
np_spectrum = 20 * np.log(np.abs(fshift))
start = datetime.datetime.now()
dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
end = datetime.datetime.now()
print("the time spent of opencv-fft:", end - start)
dft_shift = np.fft.fftshift(dft)
opencv_spectrum = 20 * np.log(cv2.magnitude(dft_shift[:, :, 0], dft_shift[:, :, 1]))
plt.subplot(231), plt.imshow(img, cmap='gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(232), plt.imshow(method1_spectrum, cmap='gray')
plt.title('method1 Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(233), plt.imshow(method2_spectrum, cmap='gray')
plt.title('method2 Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(234), plt.imshow(np_spectrum, cmap='gray')
plt.title('np Spectrum'), plt.xticks([]), plt.yticks([])
plt.subplot(235), plt.imshow(opencv_spectrum, cmap='gray')
plt.title('opencv Spectrum'), plt.xticks([]), plt.yticks([])
plt.show()
小波变换
import pywt
img = cv2.imread('../image/lena-gray.png', -1)
m,n = img.shape
coeffs = pywt.dwt2(img, 'haar')
cA, (cH, cV, cD) = coeffs
level1_img = np.zeros(img.shape)
level1_img[:math.ceil(m / 2), :math.ceil(n/2)] = cA
level1_img[:math.ceil(m / 2), math.ceil(n / 2):] = cH
level1_img[math.ceil(m / 2):, :math.ceil(n / 2)] = cV
level1_img[math.ceil(m / 2):, math.ceil(n / 2):] = cD
plt.subplot(121),plt.imshow(img, cmap = 'gray')
plt.title('Input Image'), plt.xticks([]), plt.yticks([])
plt.subplot(122),plt.imshow(level1_img, cmap = 'gray')
plt.title('level1_img'), plt.xticks([]), plt.yticks([])
plt.show()
同态滤波
import cv2
import numpy as np
from matplotlib import pyplot as plt
import math
import random
import datetime
import pywt
img = cv2.imread('../image/lena-gray.png', -1)
m,n = img.shape
def template_convolution(img,temp):
r,c = img.shape
h1,v1 = temp.shape
h = math.floor(h1 / 2)
v = math.floor(v1 / 2)
N = sum(sum(temp))
new_img = np.zeros((r,c))
for i in range(h,r-h):
for j in range(v,c-v):
if N !=0:
new_img[i][j] = abs(np.sum(img[i-h:i+h+1,j-v:j+v+1] * temp))/N
else:
new_img[i][j] = abs(np.sum(img[i-h:i+h+1,j-v:j+v+1] * temp))
return new_img
def homoenhance(img,rL=0.5,rH=2,c=2,d0=20):
if len(img.shape) > 2:
b_img = homofilter1(img[:, :, 0], rL, rH, c, d0)
g_img = homofilter1(img[:, :, 1], rL, rH, c, d0)
r_img = homofilter1(img[:, :, 2], rL, rH, c, d0)
dst_img =cv2.merge([b_img,g_img,r_img])
else:
dst_img = homofilter1(img, rL, rH, c, d0)
return dst_img
def homofilter(img,rL=0.5,rH=2,c=2,d0=20):
m,n = img.shape
if m % 2 > 0:
img = img[:m-1,:]
elif n % 2 > 0:
img = img[:,:n-1]
m1 = np.floor(m/2)
n1 = np.floor(n/2)
M, N = np.meshgrid(np.arange(-n1, n1), np.arange(-m1, m1))
D = M ** 2 + N ** 2
d0 = d0 ** 2
Huv = (rH-rL) * (1-np.exp(-c * (D / d0))) + rL
imglog = np.log(img+1)
Fuv = np.fft.fft2(imglog.astype(np.uint8))
imgifft = np.fft.ifft2(Huv*Fuv)
dst_img = np.real(np.exp(imgifft)-1)
dst_img = np.uint8(np.clip(dst_img, 0, 255))
return dst_img
def homofilter1(src, d0=10, r1=0.5, rh=2, c=4, h=2.0, l=0.5):
gray = src.copy()
if len(src.shape) > 2:
gray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
gray = np.float64(gray)
rows, cols = gray.shape
if m % 2 > 0:
gray = gray[:m-1,:]
elif n % 2 > 0:
gray = gray[:,:n-1]
gray_fft = np.fft.fft2(gray)
gray_fftshift = np.fft.fftshift(gray_fft)
dst_fftshift = np.zeros_like(gray_fftshift)
M, N = np.meshgrid(np.arange(-cols // 2, cols // 2), np.arange(-rows // 2, rows // 2))
D = np.sqrt(M ** 2 + N ** 2)
Z = (rh - r1) * (1 - np.exp(-c * (D ** 2 / d0 ** 2))) + r1
dst_fftshift = Z * gray_fftshift
dst_fftshift = (h - l) * dst_fftshift + l
dst_ifftshift = np.fft.ifftshift(dst_fftshift)
dst_ifft = np.fft.ifft2(dst_ifftshift)
dst = np.real(dst_ifft)
dst = np.uint8(np.clip(dst, 0, 255))
return dst
if __name__ == '__main__':
img = cv2.imread('../image/homotest1.png')
img =cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
homoresult1 = homoenhance(img)
if len(img.shape) > 2:
b,g,r = cv2.split(img)
img = cv2.merge([r, g, b])
b,g,r = cv2.split(homoresult1)
homoresult1 = cv2.merge([r, g, b])
plt.subplot(131),plt.imshow(img)
plt.title('original image'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(homoresult1)
plt.title('homo result'), plt.xticks([]), plt.yticks([])
plt.show()
else:
plt.subplot(131),plt.imshow(img,cmap='gray')
plt.title('original image'), plt.xticks([]), plt.yticks([])
plt.subplot(132),plt.imshow(homoresult1,cmap='gray')
plt.title('homo result'), plt.xticks([]), plt.yticks([])
plt.show()