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, (400, 300))
# 通道变换
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
frame = cv2.cvtColor(frame, cv2.COLOR_RGBA2RGB)
# 展示图片
cv2.imshow('标题', img)
# 阻塞进程等待按键
cv2.waitKey()
if cv2.waitKey(5) & 0xFF == ord('q'):
# 循环中, 按 q 退出循环
break
# 窗口名
cv2.namedWindow('monitor')
# 移动窗口
cv2.moveWindow('monitor', 800, 0)
# 改变窗口大小
cv2.resizeWindow('monitor', 600, 600)
# 销毁所有窗口
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