1. 线性变换

代码: 

import cv2
import random
import imutils
import numpy as np

# 彩色图像每个像素值是[x,y,z], 灰度图像每个像素值便是一个np.uint8
image = cv2.imread('E:/1.PNG')
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  #将彩色图像变为灰度图像(RGB彩色变灰色)

# 图像大小调整
ori_h, ori_w = image.shape[:2]   #获得原图像长宽
height, width = gray_img.shape[:2]   #获得灰度图像长宽
image = cv2.resize(image, (int(ori_w / ori_h * 400), 400), interpolation=cv2.INTER_CUBIC)  #对图像大小变换且做三次插值
gray_img = cv2.resize(gray_img, (int(width / height * 400), 400), interpolation=cv2.INTER_CUBIC)  #对图像大小变换且做三次插值

# a<0 and b=0: 图像的亮区域变暗,暗区域变亮
a, b = -0.5, 0
new_img1 = np.ones((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8) #初始化一个新图像做变换,且大小同灰度图像大小
for i in range(new_img1.shape[0]):
    for j in range(new_img1.shape[1]):
        new_img1[i][j] = gray_img[i][j] * a + b  #原始图像*a+b

# a>1: 增强图像的对比度,图像看起来更加清晰
a, b = 1.5, 20
new_img2 = np.ones((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(new_img2.shape[0]):
    for j in range(new_img2.shape[1]):
        if gray_img[i][j] * a + b > 255:
            new_img2[i][j] = 255
        else:
            new_img2[i][j] = gray_img[i][j] * a + b

# a<1: 减小了图像的对比度, 图像看起来变暗
a, b = 0.5, 0
new_img3 = np.ones((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(new_img3.shape[0]):
    for j in range(new_img3.shape[1]):
        new_img3[i][j] = gray_img[i][j] * a + b

# a=1且b≠0, 图像整体的灰度值上移或者下移, 也就是图像整体变亮或者变暗, 不会改变图像的对比度
a, b = 1, -50
new_img4 = np.ones((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(new_img4.shape[0]):
    for j in range(new_img4.shape[1]):
        pix = gray_img[i][j] * a + b
        if pix > 255:
            new_img4[i][j] = 255
        elif pix < 0:
            new_img4[i][j] = 0
        else:
            new_img4[i][j] = pix

# a=-1, b=255, 图像翻转
new_img5 = 255 - gray_img

cv2.imshow('origin', imutils.resize(image, 800))
cv2.imshow('gray', imutils.resize(gray_img, 800))
cv2.imshow('a<0 and b=0', imutils.resize(new_img1, 800))
cv2.imshow('a>1 and b>=0', imutils.resize(new_img2, 800))
cv2.imshow('a<1 and b>=0', imutils.resize(new_img3, 800))
cv2.imshow('a=1 and b><0', imutils.resize(new_img4, 800))
cv2.imshow('a=-1 and b=255', imutils.resize(new_img5, 800))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_opencv

2. 对比度拉伸

代码:

import cv2
import imutils
import numpy as np

# image = cv2.imread('E:/city.PNG')

image = cv2.imread('E:/city.PNG')
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 在灰度图进行分段线性对比度拉伸
# 此种方式变换函数把灰度级由原来的线性拉伸到整个范围[0, 255]
r_min, r_max = 255, 0
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        if gray_img[i, j] > r_max:
            r_max = gray_img[i, j]
        if gray_img[i, j] < r_min:
            r_min = gray_img[i, j]
r1, s1 = r_min, 0
r2, s2 = r_max, 255

precewise_img = np.zeros((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
k1 = s1 / r1
k3 = (255 - s2) / (255 - r2)
k2 = (s2 - s1) / (r2 - r1)
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        if r1 <= gray_img[i, j] <= r2:
            precewise_img[i, j] = k2 * (gray_img[i, j] - r1)
        elif gray_img[i, j] < r1:
            precewise_img[i, j] = k1 * gray_img[i, j]
        elif gray_img[i, j] > r2:
            precewise_img[i, j] = k3 * (gray_img[i, j] - r2)

cv2.imshow('origin image', imutils.resize(image, 480))
cv2.imshow('gray image', imutils.resize(gray_img, 480))
cv2.imshow('precewise image', imutils.resize(precewise_img, 480))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_计算机视觉_02

3. 灰度级分层

代码:

import cv2
import imutils
import numpy as np

# 在某一范围(A, B)突出灰度,其他灰度值保持不变
image = cv2.imread('E:/city.PNG')
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

r_left, r_right = 150, 230
r_min, r_max = 0, 255
level_img = np.zeros((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        if r_left <= gray_img[i, j] <= r_right:
            level_img[i, j] = r_max
        else:
            level_img[i, j] = gray_img[i, j]

cv2.imshow('origin image', imutils.resize(image, 480))
cv2.imshow('level image', imutils.resize(level_img, 480))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_灰度图像_03

4. 幂律变换

代码:

import math
import numpy as np
import cv2
import imutils

# #幂律变换 φ>1
# # image = cv2.imread('E:/1.png')
image = cv2.imread('E:/1.png')
gamma_img1 = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.float32)
for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        gamma_img1[i, j, 0] = math.pow(image[i, j, 0], 5)
        gamma_img1[i, j, 1] = math.pow(image[i, j, 1], 5)
        gamma_img1[i, j, 2] = math.pow(image[i, j, 2], 5)
cv2.normalize(gamma_img1, gamma_img1, 0, 255, cv2.NORM_MINMAX)
gamma_img1 = cv2.convertScaleAbs(gamma_img1)
cv2.imshow('image', imutils.resize(image, 400))
cv2.imshow('gamma1 transform', imutils.resize(gamma_img1, 400))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()


#幂律变换,φ<1
# image = cv2.imread('E:/1.png')
image = cv2.imread('E:/city.png')
gamma_img2 = np.zeros((image.shape[0], image.shape[1], 3), dtype=np.float32)
for i in range(image.shape[0]):
    for j in range(image.shape[1]):
        gamma_img2[i, j, 0] = math.pow(image[i, j, 0], 0.4)
        gamma_img2[i, j, 1] = math.pow(image[i, j, 1], 0.4)
        gamma_img2[i, j, 2] = math.pow(image[i, j, 2], 0.4)
cv2.normalize(gamma_img2, gamma_img2, 0, 255, cv2.NORM_MINMAX)
gamma_img2 = cv2.convertScaleAbs(gamma_img2)
cv2.imshow('image', imutils.resize(image, 400))
cv2.imshow('gamma2 transform', imutils.resize(gamma_img2, 400))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_opencv_04

5. 阈值处理

代码:

import cv2
import imutils
import numpy as np

image = cv2.imread('E:/1.png')
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#阈值处理函数:当r1=r2, s1=0, s2=L-1时,此时分段线性函数便是阈值处理函数
plist = []
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        plist.append(gray_img[i, j])
r_avg = int(sum(plist)/len(plist))
thresh_img = np.zeros((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        if gray_img[i, j] < r_avg:
            thresh_img[i, j] = 0
        else:
            thresh_img[i, j] = 255

cv2.imshow('origin image', imutils.resize(image, 480))
cv2.imshow('thresh image', imutils.resize(thresh_img, 480))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_计算机视觉_05

6. 直方图均衡化

代码:

import cv2
import imutils
import numpy as np
import matplotlib.pyplot as plt

wiki_img=cv2.imread('E:/1.PNG')
wiki_gray=cv2.cvtColor(wiki_img,cv2.COLOR_BGR2GRAY)

#对图像进行均衡化处理,增强图像对比度
wiki_equ=cv2.equalizeHist(wiki_gray)

hist=cv2.calcHist([wiki_gray],[0],None,[256],[0,256])
equ_hist=cv2.calcHist([wiki_equ],[0],None,[256],[0,256])
fig=plt.figure()
ax1=fig.add_subplot(1,2,1)
ax1.plot(hist)
ax2=fig.add_subplot(1,2,2)
ax2.plot(equ_hist)
plt.show()

cv2.imshow('wiki_origin',imutils.resize(wiki_img,400))
cv2.imshow('wiki_gray',imutils.resize(wiki_gray,400))
cv2.imshow('wiki_equ',imutils.resize(wiki_equ,400))
if cv2.waitKey(0)==27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_灰度图像_06

 

AHE图像增强python python图像增强代码_opencv_07

7. 均值滤波器

代码:

import cv2
import copy
import random
import imutils
import numpy as np

img=cv2.imread('E:/1.PNG')
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#利用OpenCV提供函数实现均值滤波
blur_img=cv2.blur(gray_img,(3,3))

#在灰度图上手动实现均值滤波器
gray_avg_img=copy.deepcopy(gray_img)   #在复制图像上修改,首先复制一份
for i in range(1,gray_img.shape[0]-1):
    for j in range(1,gray_img.shape[1]-1):
        sum_pix=sum([gray_img[l,k] for l in range(i-1,i+2) for k in range(j-1,j+2)]) #range函数写到i+2实际遍历到i+1,j+1同理
        gray_avg_img[i,j]=int(sum_pix/9) #9个点求和除均值,均值滤波实现

#在RGB彩色图上手动实现均值滤波
rgb_avg_img=copy.deepcopy(img)
for i in range(1,img.shape[0]-1):
    for j in range(1,img.shape[1]-1):  #RGB三个通道,实现三次
        sum_b_pix=sum([img[l,k,0] for l in range(i-1,i+2) for k in range(j-1,j+2)])
        sum_g_pix = sum([img[l, k, 1] for l in range(i - 1, i + 2) for k in range(j - 1, j + 2)])
        sum_r_pix = sum([img[l, k, 2] for l in range(i - 1, i + 2) for k in range(j - 1, j + 2)])
        rgb_avg_img[i,j]=[int(sum_b_pix/9),int(sum_g_pix/9),int(sum_r_pix/9)]

cv2.imshow('origin image',imutils.resize(img,500))
cv2.imshow('gray image',imutils.resize(gray_img,500))
cv2.imshow('blur image',imutils.resize(blur_img,500))
cv2.imshow('gray average image',imutils.resize(gray_avg_img,500))
cv2.imshow('rgb average image',imutils.resize(rgb_avg_img,500))
if cv2.waitKey(0) == 27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_灰度图像_08

8. 最大、最小、中值滤波器

代码:

import cv2
import copy
import random
import imutils
import numpy as np

img=cv2.imread('E:/1.PNG')
gray_img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#给灰度图像自动添加椒盐噪声
pepper_img=copy.deepcopy(gray_img)
for i in range(gray_img.shape[0]):
    for j in range(gray_img.shape[1]):
        if random.randint(0,20)==0:
            pix=random.randint(250,255)
            pepper_img[i,j]=pix

#opencv提供CV2.medianBlur()函数实现中值滤波
blur_img=cv2.medianBlur(pepper_img,5)

#自实现中值滤波
temp_arr=np.zeros((9))
median_img=copy.deepcopy(pepper_img)
max_img=copy.deepcopy(pepper_img)
min_img=copy.deepcopy(pepper_img)
for i in range(1,pepper_img.shape[0]-1):   #九个数字全部提取出来
    for j in range(1,pepper_img.shape[1]-1):
        temp_arr[0] = pepper_img[i - 1, j - 1]
        temp_arr[1] = pepper_img[i - 1, j]
        temp_arr[2] = pepper_img[i - 1, j + 1]
        temp_arr[3] = pepper_img[i - 1, j - 1]
        temp_arr[4] = pepper_img[i, j - 1]
        temp_arr[5] = pepper_img[i, j]
        temp_arr[6] = pepper_img[i, j + 1]
        temp_arr[7] = pepper_img[i + 1, j - 1]
        temp_arr[8] = pepper_img[i + 1, j]
        arr = np.sort(temp_arr)   #从小到大排序
        median_img[i,j]=arr[4]       
        max_img[i,j]=arr[8]
        min_img[i,j]=arr[0]

rgb_avg_img=copy.deepcopy(img)
for i in range(1,img.shape[0]-1):
    for j in range(1,img.shape[1]-1):
        sum_b_pix = sum([img[l,k,0] for l in range(i-1,i+2) for k in range(j-1,j+2)])
        sum_g_pix = sum([img[l, k, 1] for l in range(i - 1, i + 2) for k in range(j - 1, j + 2)])
        sum_r_pix = sum([img[l, k, 2] for l in range(i - 1, i + 2) for k in range(j - 1, j + 2)])
        rgb_avg_img[i,j]=[int(sum_b_pix/9),int(sum_g_pix/9),int(sum_r_pix/9)]

cv2.imshow('pepper image',imutils.resize(pepper_img,600))
cv2.imshow('blur image',imutils.resize(blur_img,600))
cv2.imshow('median image',imutils.resize(pepper_img,600))
cv2.imshow('mean image',imutils.resize(rgb_avg_img,600))
cv2.imshow('max image',imutils.resize(max_img,600))
cv2.imshow('min image',imutils.resize(min_img,600))

if cv2.waitKey(0)==27:
    cv2.destroyAllWindows()

效果:

AHE图像增强python python图像增强代码_opencv_09

9. 锐化滤波器

代码:

import cv2
import numpy as np
import matplotlib.pyplot as plt

#读取图像
img=cv2.imread('E:/1.PNG')
girl_img=cv2.cvtColor(img,cv2.COLOR_BGR2RGB)

#灰度化处理图像
grayImage=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

#高斯滤波
gaussianBlur=cv2.GaussianBlur(grayImage,(3,3),0)

#阈值处理
ret,binary=cv2.threshold(gaussianBlur,127,255,cv2.THRESH_BINARY) #小于127变0,在127到255之间的变1

#Roberts算子
kernelx=np.array([[-1,0],[0,1]],dtype=int)
kernely=np.array([[0,-1],[1,0]],dtype=int)
x=cv2.filter2D(binary,cv2.CV_16S,kernelx)
y=cv2.filter2D(binary,cv2.CV_16S,kernely)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Roberts=cv2.addWeighted(absX,0.5,absY,0.5,0)

#Prewitt算子
kernelx=np.array([[1,1,1],[0,0,0],[-1,-1,-1]],dtype=int)
kernely=np.array([[-1,0,1],[-1,0,1],[-1,0,1]],dtype=int)
x=cv2.filter2D(binary,cv2.CV_16S,kernelx)
y=cv2.filter2D(binary,cv2.CV_16S,kernely)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Prewitt=cv2.addWeighted(absX,0.5,absY,0.5,0)

#Sobel算子
x=cv2.Sobel(binary,cv2.CV_16S,1,0)
y=cv2.Sobel(binary,cv2.CV_16S,0,1)
absX=cv2.convertScaleAbs(x)
absY=cv2.convertScaleAbs(y)
Sobel=cv2.addWeighted(absX,0.5,absY,0.5,0)

#拉普拉斯算法
dst=cv2.Laplacian(binary,cv2.CV_16S,ksize=3)
Laplacian=cv2.convertScaleAbs(dst)

#效果图
titles=['Source Image','Binary Image','Roberts Image','Prewitt Image','Sobel Image','Laplacian Image']
images=[girl_img,binary,Roberts,Prewitt,Sobel,Laplacian]
for i in np.arange(6):
    plt.subplot(2,3,i+1),plt.imshow(images[i],'gray')  #2行3列图像显示
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

效果:

AHE图像增强python python图像增强代码_opencv_10