这大概是图像处理的“Hello World” 代码吧.
import cv2
# 读取图片
img = cv2.imread("lena-full.jpg")
# 打印图片的shape
print("Image shape:" +str(img.shape))
# 获取图片的高度和宽度
height, width = img.shape[0:2]
print("Width:"+str(width)+", height:"+str(height))
# 显示图片
cv2.imshow("img", img)
# 按任意键退出图片显示
cv2.waitKey()
# 保存图片
cv2.imwrite("lena-full-backup.jpg", img)
将以上代码保存倒hello.py 文件中,用python 命令在控制台中运行。
可以看到图片显示出来:
同时,控制台输出:
E:\Scripts\OpenCV>python hello.py
Image shape:(380, 768, 3)
Width:768, height:380
这里需要注意的是:cv2.imread函数返回的图片的shape元组结构为:(高度,宽度,通道数),第一个元素代表图像高度,而不是宽度,这个与其它的图像API有点不一样。
最后一行代码:cv2.imwrite 可以保存一张图片到指定的路径。