上节安装了opencv,然后就迫不及待的用opencv读取了图片,并显示在窗口上。
代码如下:
12 import numpy as np
13 import cv2
14
15 #Read an image
16 img = cv2.imread("/home/qqtsj/picture/cat.jpg",0)
17
18 #Display an image
19 cv2.imshow('cat_show',img)
20 cv2.waitKey(0)
21 cv2.destroyAllWindows()
22
23 #Write an image
24 cv2.imwrite('/home/qqtsj/picture/cat_scale.png',img)
代码解析:
12 import numpy as np 13 import cv2
这两行代码是导入相应的库
img = cv2.imread("/home/qqtsj/picture/cat.jpg",0)
这是opencv中的图片读取函数imread(),第一个参数是图片的路径,特别要注意这个路径,如果不对则读取出错,第二个参数表示图片的大小或者颜色,以后会更加深入的学习。
cv2.imshow('cat_show',img)
这是一个图片显示函数,显示上面读取的图片。
cv2.imwrite('/home/qqtsj/picture/cat_scale.png',img)
这是一个图片保存函数,显示的图片会根据相应的路径存储。
cv2.waitKey(0) cv2.destroyAllWindows()
waitkey()是一个等待函数,如果里面参数是0,则一直等待,直到按下任意一个键在执行下面的程序,如果不是0,则等待相应设置的时间(ms).
destroyAllWindows()函数是一个窗口清除函数,执行它显示图片窗口会清除。
下面进行程序优化,如下:
12 import numpy as np 13 import cv2 14 15 #Read an image 16 img = cv2.imread("/home/qqtsj/picture/cat.jpg",0) 17 18 #Display an image 19 cv2.imshow('cat_show',img) 20 21 k = cv2.waitKey(0) 22 23 if k == 27: 24 cv2.destroyAllWindows() 25 elif k == ord('s'): 26 cv2.imwrite('/home/qqtsj/picture/cat_scale.png',img) 27 cv2.destroyAllWindows()
如果k的值为27,该按下的键为Esc,执行清除函数。
如果按下的键为s,则保存图片,再清除。