OpenCV的图像读取显示及保存

OpenCV的图像读取显示及保存

用工具Python3.5,
使用库numpy;opencv,
从图片的导入到另存,

  1. cv2.imread(文件名,标记)读入图像,
    • cv2.IMREAD_COLOR():读入彩色图像
    • cv2.IMREAD_GRAYSCALE():以灰度模式读入图像

import numpy as np import cv2 img = cv2.imread(‘45.jpg‘,0)

2.cv2.imshow()显示图像,
* cv2.waitKey()等待键盘输入,为毫秒级
* cv2.destroyAllWindows()可以轻易删除任何我们建立的窗口,括号内输入想删除的窗口名
OpenCV的图像读取显示及保存

cv2.namedWindow(‘image‘,cv2.WINDOW_NORMAL)
cv2.imshow(‘image‘,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

3.cv2.imwrite(文件名,img)保存图像,

cv2.imwrite(‘messigray.png‘,img)

4.练习加载一个灰度图,显示图片,按下‘s’键保存后退出,或者按下ESC键退出不保存

import numpy as np
import cv2

img = cv2.imread(‘45.jpg‘,0)
cv2.imshow(‘image‘,img)
k = cv2.waitKey(0)
if k==27:
		cv2.destroyAllWindows()  #wait for ESC key to exit
elif k == ord(‘s‘):
		cv2.imwrite(‘46.png‘,img)  #wait for ‘s‘ key to save and exit
        cv2.destoryAllWindows()

如果用的是64位系统,需将key=cv2.waitKey(0)改为k=cv2.waitKey(0)&0xFF @!!

相关推荐