OpenCV 3 python学习笔记(图片IO篇)

xiaoxiao2025-05-20  53

import cv2 cv2.imread(filename[, flags])

imread支持以下格式的图片

. - Windows bitmaps - \*.bmp, \*.dib (always supported) . - JPEG files - \*.jpeg, \*.jpg, \*.jpe (see the *Notes* section) . - JPEG 2000 files - \*.jp2 (see the *Notes* section) . - Portable Network Graphics - \*.png (see the *Notes* section) . - WebP - \*.webp (see the *Notes* section) . - Portable image format - \*.pbm, \*.pgm, \*.ppm \*.pxm, \*.pnm (always supported) . - Sun rasters - \*.sr, \*.ras (always supported) . - TIFF files - \*.tiff, \*.tif (see the *Notes* section) . - OpenEXR Image files - \*.exr (see the *Notes* section) . - Radiance HDR - \*.hdr, \*.pic (always supported) . - Raster and Vector geospatial data supported by Gdal (see the *Notes* section)

如果没找到,返回an empty matrix ( Mat::data==NULL ) 第二个参数(可省略)有时候很关键,会影响后面滤波卷积的操作。 参数如下:

IMREAD_ANYCOLOR=4 #the image is read in any possible color format #(这里不知道怎么 翻译any,任一?or意指原来的?) IMREAD_ANYDEPTH=2 #返回的深度不变如果图像深度为16位则读出为16位, #32位则读出为32位,其余的转化为8位 IMREAD_COLOR=1 #返回3通道BGR图 IMREAD_GRAYSCALE=0 #返回单通道灰度图 IMREAD_LOAD_GDAL=8 #使用gdal驱动读取文件 IMREAD_UNCHANGED=-1 #返回原图,即带alpha通道

在文档里可以看到并总结为, flag>0 三通道彩色图 flag=0 灰度图 flag<0 原图

此外,还有缩放图片原大小的参数,补充如下:

IMREAD_REDUCED_GRAYSCALE_2 #如果设置了这个,图像总是转换为单通道灰度图,且尺寸缩减为1/2 IMREAD_REDUCED_COLOR_2 #图像总是转换为彩色3通道BGR且尺寸缩减为1/2. IMREAD_REDUCED_GRAYSCALE_4 #同上,灰度,缩减为1/4 IMREAD_REDUCED_COLOR_4 #同上,彩色,缩减为1/4 IMREAD_REDUCED_GRAYSCALE_8 #同上,灰度,缩减为1/8 IMREAD_REDUCED_COLOR_8 #同上,彩色,缩减为1/8

缩放这里参考了一个博主的总结,忘了看的谁的,没有链接,有时间再补。

import cv2 cv2.imwrite(filename,img)

这个函数对img有要求,要求图像为BGR或灰度格式,并且每个通道要有一定的位(bit)。Only 8-bit (or 16-bit unsigned (CV_16U) . in case of PNG, JPEG 2000, and TIFF) single-channel or 3-channel (with ‘BGR’ channel order) images . can be saved using this function.

img.shape

返回height和width和通道数

img.size

返回像素个数(文件大小)

cv2.cvtColor()

在从RGB颜色空间转换的情况下,应该明确地指定信道的顺序(RGB或BGR)。

bytearray() class bytearray([source[, encoding[, errors]]]): 如果 source 为整数,则返回一个长度为 source 的初始化数组; 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列; 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数; 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。 如果没有输入任何参数,默认就是初始化数组为0个元素。

bytearray(img) 可以将矩阵转换为标准的一维python bytearray格式 grayImage=numpy.array(buteArray).reshape(height,width) bgrImage=numpy.array(byteArray).reshape(height,width,3) 可以将butearray转换为矩阵格式

通过循环来处理python数组的效率非常低,应该尽量避免这样的操作。 使用数组索引可以高效地操作像素。

可以通过以下的操作设置感兴趣区域,用索引是循环的效率的600倍。

my_roi=img[0:100,0:100] img[200:300,200:300]=my_roi cv2.imshow(winname, mat)

这个没啥说的,起名字和传入img就可以。 记得cv2.destroyAllWindows()

转载请注明原文地址: https://www.6miu.com/read-5030428.html

最新回复(0)