数字图像处理的一些基本变换

直方图均衡化

实现函数
# 绘制直方图
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()

直方图归并化

## function: get the histogram of img
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

####   histogram Equalization  & histogram Regulation
if __name__ == '__main__':
    ### read image
    img = cv2.imread('../image/lena-gray.png',-1)
    ### Step1: get histogram
    L,hist = histogram(img)

    ### Step2: get Cumulative histogram
    ##  need to delete the gray-value that not exist in image = freq=0
    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]
    # print("Cumulative_histogram:",Cumulative_histogram)

    ### Step3 & 4: calculate the original-gray to new-gray
    ##  histogram Equalization
    # for i in Cumulative_histogram.keys():
    #     tmp = math.floor((L-1) * Cumulative_histogram[i]+0.5)
    #     Cumulative_histogram[i] = tmp

    ##  histogram Regulation SML
    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)

    # print(Cumulative_histogram)
    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
    # # print("old-gary to new-gray:",Cumulative_histogram)
    #
    ### Step5: get new image
    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)

    ### show image
    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()

模拟卷积函数



#########################  template process  ########################

##   average-neighborhood
##   template convolution
def template_convolution(img,temp):
    r,c = img.shape
    h1,v1 = temp.shape
    h = math.floor(h1 / 2)  ## threshold of row
    v = math.floor(v1 / 2)  ## threshold ofColumn
    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)
    ##   define the template
    t_3 = np.ones((3,3))
    t_11 = np.ones((11,11))
    # t_Gaussian = np.array([[1,4,7,4,1],[4,16,26,16,4],[7,26,41,26,7],[4,16,26,16,4],[1,4,5,4,1]])
    # t_Lap = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
    # new_img3 = template_convolution(img,t_3)
    # new_img11 = template_convolution(img,t_11)
    # new_imgG = template_convolution(img,t_Gaussian)
    # new_imgL = template_convolution(img,t_Lap)
    # plt.subplot(231),plt.imshow(img,cmap = 'gray')
    # plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    # plt.subplot(232),plt.imshow(new_img3,cmap = 'gray')
    # plt.title('3*3 Average'), plt.xticks([]), plt.yticks([])
    # plt.subplot(233),plt.imshow(new_img11,cmap = 'gray')
    # plt.title('11*11 Average'), plt.xticks([]), plt.yticks([])
    # plt.subplot(234),plt.imshow(new_imgG,cmap = 'gray')
    # plt.title('Gaussian Average'), plt.xticks([]), plt.yticks([])
    # plt.subplot(235),plt.imshow(new_imgL,cmap = 'gray')
    # plt.title('Laplace sharp'), plt.xticks([]), plt.yticks([])
    # plt.show()
##   template_sort for max\min\median\mean
##   flag = None is mean, =1 is max, =-1 is min =0 is median
##   temp is the size of the template(row and column are euqal)
def template_sort(img,temp,flag=None):
    r,c = img.shape
    h = math.floor(temp/2)  ## threshold of row and column
    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
##   smooth filter with template
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

########   2-dimensional discrete Fourier Transform
######   -------------------Method 1 start ----------------------
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:  # this cutoff should be optimized
        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]))))
######   -------------------Method 1 end   ----------------------

######   -------------------Method 2 start ----------------------
# 对输入数据进行倒序排列
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
            # print("forward x[%d] <==> x[%d]" % (i, j))
        k = num / 2
        while (j >= k):
            j = j - k
            k = k / 2
        j = j + k
    return input_data
# 实现1D FFT
def fft_1d(in_data, num):
    PI = np.pi
    in_data = forward_input_data(in_data,num)  # 倒序输入数据
    # 计算蝶形级数,也就是迭代次数
    M = 1  # num = 2^m
    tmp = num / 2;
    while (tmp != 1):
        M = M + 1
        tmp = tmp / 2
    # print("FFT level:%d" % M)
    for L in range(1, M + 1):
        B = int(math.pow(2, L - 1))  # B为指数函数返回值,为float,需要转换integer
        for J in range(0, B):
            P = math.pow(2, M - L) * J
            for K in range(J, num, int(math.pow(2, L))):
                # print("L:%d B:%d, J:%d, K:%d, P:%f" % (L, B, J, K, P))
                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
######   -------------------Method 2 end ----------------------

if __name__ == '__main__':
    img = cv2.imread('../image/lena-gray.png', -1)
    m,n = img.shape


    ####  method 1
    start = datetime.datetime.now()
    my_fft = (FFT2D(img))  # F(0,0)
    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))

    ###  method 2
    start = datetime.datetime.now()
    fft_result = np.zeros(img.shape, dtype=np.complex)
    # row transform
    for i in range(m):
        # 将数据转换为complex类的形式,存储在变量data中
        fft_result[i] = fft_1d(img[i, :].astype(np.complex), n)
    # column transform
    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)
    # 调用fftshift()函数转移到中间位置
    fshift = np.fft.fftshift(fft_result)
    # fft结果是复数, 其绝对值结果是振幅
    method2_spectrum = 20 * np.log(np.abs(fshift))

    ### np.fft
    # 快速傅里叶变换算法得到频率分布
    start = datetime.datetime.now()
    f = np.fft.fft2(img)
    # left_mid_spectrum = 20*np.log(np.abs(f))
    end = datetime.datetime.now()
    print("the time spent of np-fft:", end - start)
    # 默认结果中心点位置是在左上角,
    # 调用fftshift()函数转移到中间位置
    fshift = np.fft.fftshift(f)
    # fft结果是复数, 其绝对值结果是振幅
    np_spectrum = 20 * np.log(np.abs(fshift))
    # #傅里叶逆变换
    # ishift = np.fft.ifftshift(fshift)
    # iimg = np.fft.ifft2(ishift)
    # iimg = np.abs(iimg)

    #### opencv.fft
    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()
    ###
    # Resize_res = cv2.resize(img, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC)
    # M = cv2.getRotationMatrix2D((m / 2, n / 2), 45, 1)
    # Rotation_dst = cv2.warpAffine(img, M, (n, m))
    # Translation_res = cv2.warpAffine(img, np.float32([[1,0,50],[0,1,100]]), (m, n))
    # plt.subplot(231),plt.imshow(img, cmap = 'gray')
    # plt.title('Input Image'), plt.xticks([]), plt.yticks([])
    # plt.subplot(232),plt.imshow(Resize_res, cmap = 'gray')
    # plt.title('Resize'), plt.xticks([]), plt.yticks([])
    # plt.subplot(233),plt.imshow(Rotation_dst, cmap = 'gray')
    # plt.title('Rotation'), plt.xticks([]), plt.yticks([])
    # plt.subplot(234),plt.imshow(Translation_res, cmap = 'gray')
    # plt.title('Translation'), plt.xticks([]), plt.yticks([])
    # plt.show()

    # # 二维小波一级变换
    # coeffs = pywt.dwt2(img, 'haar')
    # cA, (cH, cV, cD) = coeffs
    # # 二维图像多级分解
    # coeffs = pywt.wavedec2(img, 'haar', level=2)
    # cA2, (cH2, cV2, cD2), (cH1, cV1, cD1) = 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 pywt

##########   wavelet transform  ###########
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

##########   wavelet transform  ###########
img = cv2.imread('../image/lena-gray.png', -1)
m,n = img.shape

# # 二维小波一级变换
# coeffs = pywt.dwt2(img, 'haar')
# cA, (cH, cV, cD) = coeffs
# # 二维图像多级分解
# coeffs = pywt.wavedec2(img, 'haar', level=2)
# cA2, (cH2, cV2, cD2), (cH1, cV1, cD1) = coeffs
# print(cA2.shape,cH2.shape, cV2.shape, cD2.shape,cH1.shape, cV1.shape, cD1.shape)
#
# plt.figure().suptitle('level =1 wave transform')
# 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.figure().suptitle('level = 2 wave transform')
# level2_img = np.zeros(img.shape)
# level2_img[:math.ceil(m / 4), :math.ceil(n/4)] = cA2
# level2_img[:math.ceil(m / 4), math.ceil(n/4):math.ceil(n/2)] = cH2
# level2_img[math.ceil(m / 4):math.ceil(m / 2), :math.ceil(n/4)] = cV2
# level2_img[math.ceil(m / 4):math.ceil(m / 2), math.ceil(n/4):math.ceil(n/2)] = cD2
# level2_img[:math.ceil(m / 2), math.ceil(n / 2):] = cH1
# level2_img[math.ceil(m / 2):, :math.ceil(n / 2)] = cV1
# level2_img[math.ceil(m / 2):, math.ceil(n / 2):] = cD1
# plt.subplot(121),plt.imshow(img, cmap = 'gray')
# plt.title('Input Image'), plt.xticks([]), plt.yticks([])
# plt.subplot(122),plt.imshow(level2_img, cmap = 'gray')
# plt.title('level1_img'), plt.xticks([]), plt.yticks([])
# plt.show()

##########   image enhancement  ###########
def template_convolution(img,temp):
    r,c = img.shape
    h1,v1 = temp.shape
    h = math.floor(h1 / 2)  ## threshold of row
    v = math.floor(v1 / 2)  ## threshold ofColumn
    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
### np.fft
# # #快速傅里叶变换算法得到频率分布
# f = np.fft.fft2(img)
# # 默认结果中心点位置是在左上角,
# # 调用fftshift()函数转移到中间位置
# fshift = np.fft.fftshift(f)
# # # fft结果是复数, 其绝对值结果是振幅
# np_spectrum = 20 * np.log(np.abs(fshift))
# # # low pass filter
# fm, fn = fshift.shape
# dm, dn = fm/2, fn/2
# low_pass_spectrum = np.zeros((fm,fn))
# low_pass_filter = np.array(fshift)
# low_pass_filter[int((fm-dm)/2):int((fm+dm)/2),int((fn-dn)/2):int((fn+dn)/2)] = 0
# low_pass_filter = fshift - low_pass_filter
# low_pass_spectrum[int((fm-dm)/2):int((fm+dm)/2),int((fn-dn)/2):int((fn+dn)/2)]\
#     =np_spectrum[int((fm-dm)/2):int((fm+dm)/2),int((fn-dn)/2):int((fn+dn)/2)]
# #
# high_pass_filter = fshift - low_pass_filter
# high_pass_spectrum = np_spectrum - low_pass_spectrum
# #
# # # #傅里叶逆变换
# ishift = np.fft.ifftshift(fshift)
# iimg = np.fft.ifft2(ishift)
# iimg = np.abs(iimg)
# # #
# ishift = np.fft.ifftshift(low_pass_filter)
# iimg1 = np.fft.ifft2(ishift)
# iimg1 = np.abs(iimg1)
# # #
# ishift = np.fft.ifftshift(high_pass_filter)
# iimg2 = np.fft.ifft2(ishift)
# iimg2 = np.abs(iimg2)
# #
# t_3 = np.ones((3,3))
# t_11 = np.ones((11,11))
# t_Gaussian = np.array([[1,4,7,4,1],[4,16,26,16,4],[7,26,41,26,7],[4,16,26,16,4],[1,4,5,4,1]])
# t_Lap = np.array([[-1,-1,-1],[-1,8,-1],[-1,-1,-1]])
# new_img11 = template_convolution(img,t_11)
# new_imgG = template_convolution(img,t_Gaussian)
# new_imgL = template_convolution(img,t_Lap)
# # #
# plt.figure().suptitle('Frequency domain image enhancement')
# plt.subplot(241),plt.imshow(img, cmap = 'gray')
# plt.title('Input Image'), plt.xticks([]), plt.yticks([])
# plt.subplot(242),plt.imshow(np_spectrum, cmap = 'gray')
# plt.title('np_spectrum'), plt.xticks([]), plt.yticks([])
# plt.subplot(243),plt.imshow(low_pass_spectrum, cmap = 'gray')
# plt.title('low_pass_spectrum'), plt.xticks([]), plt.yticks([])
# plt.subplot(244),plt.imshow(high_pass_spectrum, cmap = 'gray')
# plt.title('high_pass_spectrum'), plt.xticks([]), plt.yticks([])
# plt.subplot(246),plt.imshow(iimg, cmap = 'gray')
# plt.title('np_Inverse'), plt.xticks([]), plt.yticks([])
# plt.subplot(247),plt.imshow(iimg1, cmap = 'gray')
# plt.title('low_Inverse'), plt.xticks([]), plt.yticks([])
# plt.subplot(248),plt.imshow(iimg2, cmap = 'gray')
# plt.title('high_Inverse'), plt.xticks([]), plt.yticks([])
# # plt.show()
# #
# plt.figure().suptitle('Spatial domain image enhancement')
# plt.subplot(131),plt.imshow(new_img11,cmap = 'gray')
# plt.title('Conv 11*11 Average'), plt.xticks([]), plt.yticks([])
# plt.subplot(132),plt.imshow(new_imgG,cmap = 'gray')
# plt.title('Conv Gaussian Average'), plt.xticks([]), plt.yticks([])
# plt.subplot(133),plt.imshow(new_imgL,cmap = 'gray')
# plt.title('Conv Laplace sharp'), plt.xticks([]), plt.yticks([])
# plt.show()

##############  homo enhance
####  the parameter of H(u,v)
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):
    ### Build H(u,v)
    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)                    ### log
    Fuv = np.fft.fft2(imglog.astype(np.uint8))       ### FFT
    imgifft = np.fft.ifft2(Huv*Fuv)           ### H(u,v)*F(u,v)  and iFFT
    dst_img = np.real(np.exp(imgifft)-1)      ### exp
    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()


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值