import numpy as np
import cv2
fn = '图片路径'
# 读取为 ndarray
img: np.ndarray = cv2.imread(fn)
# imread 不能读中文路径的替代方案
img: np.ndarray = cv2.imdecode(np.fromfile(
fn, dtype=np.uint8), cv2.IMREAD_COLOR)
# 保存为文件
cv2.imwrite(fn, img)
# imwrite 不能保存中文路径的替代方案
cv2.imencode('.png', img)[1].tofile(fn)
# 缩放
img = cv2.resize(img, (w, h))
# 按宽高比率缩放
img = cv2.resize(img, (0, 0),fx=3,fy=1)
# 通道变换
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img, cv2.COLOR_RGBA2RGB)
# 通道提取
b, g, r = cv2.split(img)
# 展示图片
cv2.imshow('标题', img)
# 阻塞进程等待按键
cv2.waitKey()
if cv2.waitKey(5) & 0xFF == ord('q'):
# 循环中, 按 q 退出循环
break
# 窗口名
cv2.namedWindow('monitor')
# 移动窗口
cv2.moveWindow('monitor', x, y)
# 改变窗口大小
cv2.resizeWindow('monitor', w, h)
# 销毁所有窗口
cv2.destroyAllWindows()
# 裁剪
def crop(img: np.ndarray):
"""
去掉上下, 中间裁剪为3块
"""
h, w, c = img.shape
h1 = h//7*2
h2 = h//7*5
w1 = w//3
img1 = img[h1:h2, :w1]
img2 = img[h1:h2, w1:w1*2]
img3 = img[h1:h2, w1*2:]
return img1, img2, img3
# 边缘填充
top, bottom, left, right = 100,100,100,100
img = cv2.copyMakeBorder(img,top,bottom,left,right,borderType=cv2.BORDER_CONSTANT,value = 0)
# 不越界加法
img = cv2.add(img1,img2)
# 图像融合 安权重相加 b:亮度偏置
img = cv2.addWeighted(img1,0.4,img2,0.6, b)
# 阈值操作
ret, nimg = cv2.threshold(img, thresh, maxval, type)
# 滤波
# 均值滤波
img = cv2.blur(img,(3,3))
# 方框滤波
img = cv2.boxFilter(img,-1,(3,3),normalize=True)
# 高斯滤波
img = cv2.GaussianBlur(img,(5,5),1)
# 中值滤波
img = cv2.medianBlur(img,5)