安装
pip install opencv-python
读取本地文件并显示
r = cv2.imread("./image/20230527_150320-1.jpg")
print("image_shape: ", r.shape)
cv2.imshow("img", r)
# 加上 waitKey 否则会直接退出
cv2.waitKey(0)
读取网格图片并显示
resp = requests.get(url="http://example.com/example.jpg")
image = cv2.imdecode(np.frombuffer(resp.content, np.uint8), cv2.IMREAD_UNCHANGED)
cv2.imshow("image", image)
cv2.waitKey(0)
- cv2.IMREAD_COLOR: 将图像解码为RGB彩色图像
- cv2.IMREAD_GRAYSCALE: 将图像解码为灰度图像
- cv2.IMREAD_UNCHANGED: 不进行任何转换,以原格式解码
手动裁剪图片
import os
import cv2
dir_path = 'image/'
imgs = os.listdir(dir_path)
for img_name in imgs:
filename = os.path.join(dir_path, img_name)
print(filename)
img = cv2.imread(filename)
x, y, w, h = cv2.selectROI("select the area", img) # 手动选择兴趣区域
crop = img[y:y + h, x:x + w] # 裁剪区域
save_path = 'resize/' + img_name
cv2.imwrite(save_path, crop)