图像处理之python(基础学习)

图像的基本处理



1. 读取图片
2. 保存图片
3. 颜色空间转换
4. 获取图片属性
5. 缩放图片
6. 平移图片
7. 旋转图片
8. 仿射变换
9. 通道的拆分/合并处理
10. 图片添加边距


import numpy as np
import cv2 as cv        # OpenCv库

# 为了一直显示图片  在显示图片后加上
cv.waitKey(0)                 # 等待输入  一直显示当前图片

# 销毁所有窗口
cv.destroyAllWindows()

1、读取图片

img = cv.imread(r".\1.png")     # 相对路径
# 这里用的相对路径  当然也可以用绝对路径

函数解析:

可以go to declaration查看使用说明


函数原型:
def imread(filename, flags=None): # real signature unknown; restored from doc
参数含义:
@param filename Name of file to be loaded.
@param flags Flag that can take values of cv::ImreadModes


参数说明:

  1. filename没什么可说的,绝对地址或者相对地址
  2. 重点说明一下flags参数

Enumerator

  1. IMREAD_UNCHANGED:不进行转化,比如保存为了16位的图片,读取出来仍然为16位。
    If set, return the loaded image as is (with alpha channel, otherwise it gets cropped).
  2. IMREAD_GRAYSCALE :进行转化为灰度图,比如保存为了16位的图片,读取出来为8位,类型为CV_8UC1
    If set, always convert image to the single channel grayscale image.
  3. IMREAD_COLOR :进行转化为三通道图像。
    If set, always convert image to the 3 channel BGR color image.
  4. IMREAD_ANYDEPTH :如果图像深度为16位则读出为16位,32位则读出为32位,其余的转化为8位。
    If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit.
  5. IMREAD_ANYCOLOR
    If set, the image is read in any possible color format.
  6. IMREAD_LOAD_GDAL 使用GDAL驱动读取文件,GDAL(Geospatial Data Abstraction Library)是一个在X/MIT许可协议下的开源栅格空间数据转换库。它利用抽象数据模型来表达所支持的各种文件格式。它还有一系列命令行工具来进行数据转换和处理。
    If set, use the gdal driver for loading the image.


1、If the image cannot be read (because of missing file, improper permissions, unsupported or invalid format), the function returns an empty matrix ( Mat::data==NULL ).
翻译过来,当由于某种原因读取不到文件时,返回空矩阵!
2、该函数支持的文件类型:
. - 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)
3、注意点:
(1)、 The function determines the type of an image by the content, not by the file extension.
读取的图片的形式是由图片本身的内容决定,而不是由图片的后缀名决定
(2)、In the case of color images, the decoded images will have the channels stored in B G R order.
(3)、其他

2、保存图片

3、颜色转换

使用cvtColor函数


函数作用:
  The function converts an input image from one color space to another. In case of a transformation to-from RGB color space, the order of the channels should be specified explicitly (RGB or BGR)(指定输入图像颜色空间类型).
  Note that the default color format in OpenCV is often referred to as RGB but it is actually BGR (the bytes are reversed).
  So the first byte in a standard (24-bit) color image will be an 8-bit Blue component, the second byte will be Green, and the third byte will be Red. The fourth, fifth, and sixth bytes would then be the second pixel (Blue, then Green, then Red), and so on.
OpenCv默认的颜色制式是BGR而非RGB。
. The conventional ranges for R, G, and B channel values are:
. - 0 to 255 for CV_8U images
. - 0 to 65535 for CV_16U images
. - 0 to 1 for CV_32F images

对于线性变换来说,这些取值范围是无关紧要的。
但是对于非线性转换,输入的RGB图像必须归一化到其对应的取值范围来或得最终正确的转换结果,
  例如从RGB->L*u*v转换。如果从一个8-bit类型图像不经过任何缩放(scaling)直接转换为32-bit浮点型图像,函数将会以0-255的取值范围来取代0-1的取值范围,所以在使用cvtColor函数之前需要对图像进行缩放

img *= 1./255;
cvtColor(img, img, CV_BGR2Luv);

如果对8-bit图像使用cvtColor()函数进行转换将会由一些信息丢失。函数可以做下面类型的转换,需要说明的是在opencv2.x时颜色空间转换code用的宏定义是CV_前缀开头,而在opencv3.x版本其颜色空间转换code宏定义更改为COLOR_开头,而经验证,2.4.13版本中opencv同事支持这两种形式的写法。故下面表格会将两种code类型同时列出,以供参考:
这里写图片描述

这里列出的类型并不齐全,但是对于一般的图像处理已经够用。需要特别说明的是RGB–>GRAY的转换是我们常用的转换格式,其转换公式如下:

这里写图片描述

上图中出现的RGBA格式图片,RGBA是代表Red(红色)、Green(绿色)、Blue(蓝色)和Alpha的色彩空间。虽然它有时候被描述为一个颜色空间,但是它其实是RGB模型附加了额外的信息,可以属于任何一种RGB颜色空间。Alpha参数一般用作不透明度参数,如果一个像素的alpha通道数值为0%,那它就是完全透明的也就是肉眼不可见,而数值为100%则意味着一个完全不透明的像素,传统的数字图像就是alpha值为100%。
需要注意的是cvtColor()函数不能直接将RGB图像转换为二值图像(Binary Image),需要借助threshold()函数,其具体用法请查阅threshold().

代码如下:

# 使用opencv读取图像,直接返回numpy.ndarray 对象,通道顺序为BGR ,注意是BGR,通道值默认范围0-255。
img = cv.imread(r".\1.png")     # 相对路径
cv.imshow("IMAGE_BGR",img)       # 在Image窗口中显示图片img

img_gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)   # 将彩色图像转换为灰度图像
img_hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)     # 将彩色图像转换为HSV图像
cv.imshow("IMAGE_GRAY",img_gray)
cv.imshow("IMAGE_HSV", img_hsv)


函数原型:

def cvtColor(src, code, dst=None, dstCn=None): # real signature unknown; restored from doc

参数意义:

. @param src input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision
. floating-point.
. @param dst output image of the same size and depth as src.
. @param code color space conversion code (see #ColorConversionCodes).
. @param dstCn number of channels in the destination image; if the parameter is 0, the number of the
. channels is derived automatically from src and code.


4、获得图片属性:

sp = img.shape    # 图片的大小  像素 高  宽    通道数  
# sp[0] 高
# sp[1] 宽
# sp[2] 通道数
img.size     # 像素点个数

5、缩放图片:

size = img_gray.shape
temping = cv.resize(img_gray,((int)(size[1]*0.1),(int)(size[0]*0.5)),interpolation=cv.INTER_LINEAR)
# 等同上述一行代码
temping = cv.resize(img_gray,None, fx=0.5, fy=0.5, interpolation=cv.INTER_LINEAR)
cv.imshow('img_gray2',temping)

6、平移图片

rows,cols = img_gray.shape

M = np.float32([[1,0,100],[0,1,50]])
dst = cv.warpAffine(img,M,(cols,rows))

cv.imshow('img_gray3',dst)
cv.waitKey(0)
cv.destroyAllWindows()

7、旋转图片

rows,cols = img_gray.shape

M = cv.getRotationMatrix2D((cols/2,rows/2),90,1)
dst = cv.warpAffine(img,M,(cols,rows))

cv.imshow('img_gray4',dst)

8、仿射变换

rows,cols,ch = img.shape

pts1 = np.float32([[50,50],[200,50],[50,200]])
pts2 = np.float32([[10,100],[200,50],[100,250]])

M = cv.getAffineTransform(pts1,pts2)

dst = cv.warpAffine(img,M,(cols,rows))

cv.imshow('image',dst)

9、通道的拆分/合并处理

b,g,r = cv.split(img)
img = cv.merge((b,g,r))

10、图片添加边距

未完待续!!!

猜你喜欢

转载自blog.csdn.net/weixin_39540045/article/details/80542651