读取图像和展示图像
python
import matplotlib.pyplot as plt
import numpy as np
import cv2
def matshow(title='image',image=None,gray=False):
if isinstance(image,np.ndarray):
if len(image.shape) == 2:
pass
elif gray == True:
image = cv2.cvtColor(image , cv2.COLOR_BGR2GRAY)。# 颜色空间转换
else:
image = cv2.cvtColor(image , cv2.COLOR_BGR2RGB) # 以彩色模式加载图片
plt.figure()
# 常常用来显示灰度图像
plt.imshow(image,cmap='gray')。#只会影响灰度图像的显示,不影三通道图像
plt.axis('off')
plt.title(title)
plt.show()
读取彩色图片并显示
python
im = cv2.imread(r'lena.jpeg',1)
matshow('test',im)
opencv使用BGR作为默认的颜色空间,显示图片时需要转换成RGB。
灰度变化
对每一个像素点应用灰度转换函数。
反转:对于每一个像素点,黑变白,白变和。
y = − x + 255 y= -x + 255 y=−x+255
灰度拉伸:增加相邻像素的灰度差别
y = 2 × x y = 2 \times x y=2×x
灰度压缩:减少相邻像素的灰度差别
y = 0.8 × x y=0.8\times x y=0.8×x
伽马矫正:灰度的指数变换映射
y = ( x 255 ) α × β y =( \frac{x}{255} )^\alpha \times \beta y=(255x)α×β
python
# 这是变换函数
def linear_trans(img , k , b=0):
trans_list = [(np.float32(x) * k + b) for x in range(256)]
trans_table = np.array(trans_list)
trans_table[trans_table > 255] = 255
trans_table[trans_table < 0] = 0
trans_table = np.round(trans_table).astype(np.uint8)
return cv2.LUT(img , trans_table)
# 高斯变换函数
def gamma_trans(img , gamma):
gamma_list = [np.power(x / 255.0 , gamma) * 255.0 for x in range(256)]
gamma_table = np.round(np.array(gamma_list)).astype(np.uint8)
return cv2.LUT(img,gamma_table)
im2 = linear_trans(im , -1 , 255)
print(im2.shape)
matshow('inver' , linear_trans(im , -1 , 255),True)
matshow('inver2' , linear_trans(im , 1 , 2),True)
matshow('inver3' , linear_trans(im , 0.8),True)
几何变换
python
# 平移
def translate(img,x,y):
(h,w) = img.shape[:2]
M = np.float32([[1,0,x],[0,1,y]])
shifted = cv2.warpAffine(img,M,(w,h))
return shifted
matshow('orig',im)
shifted = translate(im,0,50) # 下移50
matshow('shifted',shifted)
shifted = translate(im,-100,0) # 左移100
matshow('shifted2',shifted)
shifted = translate(im,50,100) # 右移50 下移100
matshow('shifted3',shifted)
# 旋转
def rotate(img,angle,center=None,scale=1.0):
(h,w) = img.shape[:2]
if center is None:
# 没有定义中心点 默认是图片的长宽的中心
center = (w/2 , h/2)
M = cv2.getRotationMatrix2D(center , angle , scale)
rotate = cv2.warpAffine(img , M , (w , h))
return rotate
matshow('r1',rotate(im,45))
matshow('r2',rotate(im,-20))
matshow('r3',rotate(im,90))
# 镜像
matshow('flip ver',cv2.flip(im,0)) # 水平
matshow('flip hor',cv2.flip(im,1))。# 竖直
# 缩放
matshow('resize1',cv2.resize(im,(200,300),interpolation=cv2.INTER_NEAREST)) # 邻近插值
matshow('resize2',cv2.resize(im,(800,600),interpolation=cv2.INTER_LINEAR)) #线性插值
仿射函数
A = ( 1 0 x 0 1 y ) A = \begin{pmatrix} 1 & 0 & x \\ 0 & 1& y \end{pmatrix} A=(1001xy)
位置
B = ( w h 1 ) B = \begin{pmatrix} w \\ h \\ 1 \end{pmatrix} B= wh1
图像滤波
- 均值滤波
- 中值滤波
- 高斯滤波
python
matshow('median_blur',cv2.medianBlur(im,5)) # 中值
matshow('mean_blur',cv2.blur(im , (3,3)))# 均值
im_gaus = cv2.GaussianBlur(im,(5,5),0) # 高斯滤波。考虑了远近