目录
1、灰度图像二值化
import cv2
img_input = cv2.imread('cameraman.tif', cv2.IMREAD_GRAYSCALE)
# 当阈值较大时,会使得像素值低于160的像素点被划分为黑色
ret, im_binary = cv2.threshold(img_input, 160, 255, cv2.THRESH_BINARY)
# 显示图像
cv2.imshow("input",img_input)
cv2.imshow("output",im_binary)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
2、图像反转
import cv2
img = cv2.imread('lena_gray_256.tif') # 前头加 r 是消除反斜杠转义
reverse_img = 255 - img
# 显示图像
cv2.imshow("input",img)
cv2.imshow("output",reverse_img)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
3、对数变换
import cv2
import numpy as np
img_input = cv2.imread('pollens.tif')
# 其中21为尺度比例常数,可按实际情况进行修改
img_output = 21*np.log(1.0+ img_input)
img_output = np.uint8(img_output +0.5)
# 显示图像
cv2.imshow("input",img_input)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imshow("output",img_output)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
4、图像加法
import cv2
img_input1 = cv2.imread('cameraman_256.tif')
img_input2 = cv2.imread('lena_gray_256.tif')
reverse_img = cv2.add(img_input1, img_input2)
# 显示图像
cv2.imshow("reverse_img",reverse_img)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
5、图像减法
import cv2
img_input1 = cv2.imread('lena_gray_256.tif')
img_input2 = cv2.imread('cameraman_256.tif')
reverse_img = cv2.subtract(img_input1, img_input2)
# 显示图像
cv2.imshow("reverse_img",reverse_img)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
6、图像融合
# 图像融合中,图像大小要相同
import cv2
src1 = cv2.imread('lena_color_512.tif')
src2 = cv2.imread('peppers_color.tif')
# 0.4、0.6为对应图像融合比例,100为亮度
result = cv2.addWeighted(src1, 0.4, src2, 0.6, 100)
# 显示图像
cv2.imshow("result",result)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
7、直方图均衡化
import cv2
img = cv2.imread('Fig1027(a).tif', cv2.IMREAD_GRAYSCALE)
equ = cv2.equalizeHist(img)
# 显示图像
cv2.imshow("input",img)
cv2.imshow("output",equ)
# 等待显示
cv2.waitKey(0)
cv2.destroyAllWindows()
8、图像平滑(均值滤波、中值滤波、高斯滤波)
import cv2
img = cv2.imread('lena_color_512_saltpepper.jpg ') # 读取图片
result_blur = cv2.blur(img, (3, 3)) #均值滤波
result_GaussianBlur = cv2.GaussianBlur(img, (3, 3), 0) # 高斯滤波
result_medianBlur = cv2.medianBlur(img, 3) # 中值滤波
cv2.imshow('original', img)
cv2.imshow('result_blur', result_blur)
cv2.imshow('result_GaussianBlur', result_GaussianBlur)
cv2.imshow('result_medianBlur', result_medianBlur)
cv2.waitKey(0)
9、图像锐化 拉普拉斯模板(线性)
import cv2
import numpy as np
src = cv2.imread('circuit.tif')
kernel = np.array([[-1, -1, -1],
[-1, 9, -1],
[-1, -1, -1]])
dst = cv2.filter2D(src, -1, kernel)
cv2.imshow('original', src)
cv2.imshow('dst', dst)
cv2.imshow('src+dst', src+dst)
cv2.waitKey(0)
cv2.destroyAllWindows()
10、图像锐化 梯度模板(非线性)
import cv2
import numpy as np
src = cv2.imread('lena_gray_256.tif')
sobelx = cv2.Sobel(src, cv2.CV_64F, 1, 0)
sobely = cv2.Sobel(src, cv2.CV_64F, 0, 1)
sobelx = cv2.convertScaleAbs(sobelx)
sobely = cv2.convertScaleAbs(sobely)
sobelxy = cv2.addWeighted(sobelx, 0.5, sobely, 0.5, 0)
cv2.imshow("original", src)
cv2.imshow("xy", sobelxy)
cv2.imshow("original+xy", src+sobelxy)
cv2.waitKey(0)
cv2.destroyAllWindows()