python及opencv环境搭建完成后,开始正式的学习阶段。
使用工具Python3.5,
使用库numpy;opencv,
一.OpenCV的图像读取显示及保存
1. cv2.imread(filename、flag)读入图像
(1)fliename
按照网上的说法,opencv的imread()不支持右斜线的路径书写(“D:\img\1.jpg”)方式。但是!!!经过实验发现imread()除了不支持单右斜线形式,其他斜线形式都支持!!!比如双右斜线形式(“D:\\img\\1.jpg”)、双左斜线形式(“D://img//1.jpg”)、单左斜线形式(“D:/img/1.jpg”)、前述三种斜线混合型式也是支持的。
(2)flag
有关第2个参数,官方说明是这样的:
Flags specifying the color type of a loaded image:
- CV_LOAD_IMAGE_ANYDEPTH - If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
- CV_LOAD_IMAGE_COLOR - If set, always convert image to the color one
- CV_LOAD_IMAGE_GRAYSCALE - If set, always convert image to the grayscale one
- >0 Return a 3-channel color image.
Note
In the current implementation the alpha channel, if any, is stripped from the output image. Use negative value if you need the alpha channel.
- =0 Return a grayscale image.
- <0 Return the loaded image as is (with alpha channel).
flag是一个标记位,取值从-1到3,也有对应的宏定义。
CV_LOAD_IMAGE_UNCHANGED – 在每个通道中,每个像素的位深为8 bit,通道数(颜色)保持不变。
CV_LOAD_IMAGE_GRAYSCALE – 位深=8 bit 通道数=1(颜色变灰)
CV_LOAD_IMAGE_COLOR -位深=?, 通道数=3
CV_LOAD_IMAGE_ANYDEPTH – 位深不变 ,通道数=?
CV_LOAD_IMAGE_ANYCOLOR – 位深=?, 通道数不变
(3)用法
import cv2
img = cv2.imread('45.jpg',0)
2. cv2.imshow()显示图像
cv2.imshow('image',img)
单独使用imshow的时候会生成一个命名为‘image’的窗口来显示图像。但是默认的创建窗口的namedWindow参数为WINDOW_AUTOSIZE。窗口大小会自动调整以适应所显示的图像,但是不能更改大小。
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
在调用cv2.imshow('image',img)namedWindow参数为WINDOW_NORMAL,则用户便可以改变窗口的大小(没有限制)。
3. cv2.imwrite(filename、img)保存图像
bool imwrite(const string& filename, InputArray img, const vector<int>& params=vector<int>());
(1)filename
待写入的文件名。保存图像的格式由扩展名决定。
(2)img
一般为一个Mat类型的图像。
图像要求:单通道或三通道图像,8bit或16bit无符号数,其他类型输入需要用函数进行转换 (这个还是挺重要的,之前想存一个float型的Mat, 发现并没有好的办法,最后解决方案是存成xml文件):
- convertTo: 转换数据类型不同的Mat
- cvtColor: 转换不同通道的Mat (利用第四个参数)
(3)params
特定格式保存的参数编码:
- JPEG:params表示0到100的图片质量(CV_IMWRITE_JPEG_QUALITY),默认值为95;
- PNG:params表示压缩级别(CV_IMWRITE_PNG_COMPRESSION),从0到9,其值越大,压缩尺寸越小,压缩时间越长;
- PPM / PGM / PBM:params表示二进制格式标志(CV_IMWRITE_PXM_BINARY),取值为0或1,默认值是1。
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是需要掌握的绘图库
示例用法如下:
import numpy as np
import cv2from 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()