使用工具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()可以輕易删除任何我們建立的視窗,括号内輸入想删除的視窗名
![](https://box.kancloud.cn/691a8db1307845e260df181db45e8103_526x149.jpg)
~~~
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 @!!
5.Matplotlib是牛X的繪圖庫,先簡單介紹顯示圖像
~~~
import numpy as np
import cv2
from matplotlib import pyplot as plt
img =cv2.imread('45.jpg',0)
plt.imshow(img,cmap='gray',interpolation = 'bicubic')
plt.xticks([]),plt.yticks([]) #to hide tick values on X and Y axis
plt.show()
~~~