opencv 图像的基本处理

188 阅读2分钟
import cv2
import numpy as np
import matplotlib.pyplot as plt
# 一、图像的读取
filename = 'C:\Users\86186\Desktop\lemn.png'
# imread(const string& filename,int flag = 1)
# flag=-1,0,1,2,3,4  1:8位深度,3通道 0:8位深度,1通道
src = cv2.imread(filename, 1)

# 三、展示图片,并给窗口命名
cv2.imshow('img', src)
# 图片在敲击键盘0时才关闭
cv2.waitKey(0)
# cv2.destroyAllWindows

# 二、图像的性质
# 返回宽度、长度、通道信息 (512,512,3)
print(src.shape)
print(src.shape[:2])
print(src.shape[:3])
print(src.shape[0])
print(src.shape[1])
print(src.size)
print(src.dtype) # 数据类型对象 (dtype) 无符号整数(0 to 255)

# 四、保存图像
img = np.array([
[[255, 0, 0], [0, 255, 0], [0, 0, 255]],
[[255, 255, 0], [255, 0, 255], [0, 255, 255]],
[[255, 255, 255], [128, 128, 128], [0, 0, 0]],], dtype=np.uint8)
plt.imsave('img_pyplot.jpg',img)

# imwrite函数功能:用于将图像保存到指定的文件,可以为各种格式的图像。
# cv2.imwrite(file,img,num)
# (文件名 要保存的图像 特定的格式)
# 对于JPEG,其表示的是图像的质量,用0 - 100的整数表示,默认95;
# 对于png ,第三个参数表示的是压缩级别,默认为3。
# cv2.IMWRITE_JPEG_QUALITY类型为 long ,必须转换成 int •
# cv2.IMWRITE_PNG_COMPRESSION, 从0到9 压缩级别越高图像
cv2.imwrite('img_cv2.jpg', img)
cv2.imwrite('1.png', img, [int(cv2.IMWRITE_JPEG_QUALITY), 95])
cv2.imwrite('1.png', img, [int(cv2.IMWRITE_PNG_COMPRESSION), 9])

# 五、图像的变换
# 1、图像复制 src.copy()
srccopy = src.copy()
cv2.imshow('srccopy.png',srccopy)
cv2.waitKey(0)

# 2、图像反转 cv2.flip(src,flipcode) code=0 x轴反转 1 y轴反转 -1 同时
cv2.imshow('srcflip', cv2.flip(srccopy, -1))
cv2.waitKey(0)

# 3、图像缩放 cv2.resize
# cv2.resize(src, dsize, fx, fy, interpolation)
# interpolation,插值方式;cv2.INTER_NEAREST,cv.INTER_LINEAR,cv2.INTER_CUBIC等;
# 默认情况下,所有的放缩都使用cv.INTER_LINEAR

res = cv2.resize(srccopy, None, fx=1, fy=2,interpolation =cv2.INTER_CUBIC )
cv2.imshow('res.png', res)
cv2.waitKey(0)

# 4、图像的仿射变换
# cv2.warpAffine(src,M,dsize[,dst[,flags[,borderMode[,borderValue]]]])
# --src表示原始图像
#  --M是一个2*3的变换矩阵,可以实现平移、旋转等多种操作
#  --dsize为变换后的图像大小
#  --flags为插值方式,默认为cv2.INTER_LINEAR
#  --borderMode为边界类型,默认为cv2.BORDER_CONSTANT
#  --borderValue为边界值,默认为0

h = srccopy.shape[0]
w = srccopy.shape[1]
dsize = (h, w)
m=np.float32([[1,0,100],[0,1,50]])
src2 = cv2.warpAffine(srccopy,m,dsize)
cv2.imshow('src2.png', src2)
cv2.waitKey(0)

# 5、获得旋转矩阵
n = cv2.getRotationMatrix2D((w/2,h/2),60,0.5)
src3 = cv2.warpAffine(srccopy,n,dsize)
cv2.imshow('rotation',src3)
cv2.waitKey(0)