数字图像处理
随着人工智能发展,数字图像处理显得尤为作用,体现在如何让计算机代替人眼进行识别检测一些物体,进而对一些生活场景进行监控,控制以及处理。
图像的读取
"""
@Time : 2024/4/28 22:14
@Author : chensong
@File : 图像属性与数据类型转换.py
@Desc :
"""
# 图像属性与数据类型转换
import cv2 as cv
import numpy as np
if __name__ == '__main__':
# 读取图像,支持 bmp、jpg、png、tiff 等常用格式
filepath = "./images/Lena.tif" # 读取文件的路径
img = cv.imread(filepath, flags=1) # flags=1 读取彩色图像(BGR)
print(img)
gray = cv.imread(filepath, flags=0) # flags=0 读取为灰度图像
print(gray)
cv.imshow('lena灰度图',gray)
cv.waitKey(0)
cv.destroyAllWindows()
# {}中填入函数变量 opencv读取的是BGR格式数据
# 打印数组维度
print("Ndim of img(BGR): {}, gray: {}".format(img.ndim, gray.ndim))
# number of rows, columns and channels打印数组行列数以及通道数
print("Shape of img(BGR): {}, gray: {}".format(img.shape, gray.shape))
# 打印数组元素个数
print("Size of img(BGR): {}, gray: {}".format(img.size, gray.size)) # size = rows * columns * channels
# 将数组元素类型转为32bit浮点型
imgFloat = img.astype(np.float32) / 255
# 打印数组原始的数据类型
print("Dtype of img(BGR): {}, gray: {}".format(img.dtype, gray.dtype)) # uint8
# 打饮转换后的数组数据类型
print("Dtype of imgFloat: {}".format(imgFloat.dtype)) # float32```
## 结果如下
D:\personalSoft\anaconda3\python.exe D:\pythonProject1\opencv函数大全\图像属性与数据类型转换.py
[[[125 137 226]
[125 137 226]
[133 137 223]
...
[122 148 230]
[110 130 221]
[ 90 99 200]]
[[125 137 226]
[125 137 226]
[133 137 223]
...
[122 148 230]
[110 130 221]
[ 90 99 200]]
[[125 137 226]
[125 137 226]
[133 137 223]
...
[122 148 230]
[110 130 221]
[ 90 99 200]]
...
[[ 60 18 84]
[ 60 18 84]
[ 58 27 92]
...
[ 84 73 173]
[ 76 68 172]
[ 79 62 177]]
[[ 57 22 82]
[ 57 22 82]
[ 62 32 96]
...
[ 79 70 179]
[ 81 71 181]
[ 81 74 185]]
[[ 57 22 82]
[ 57 22 82]
[ 62 32 96]
...
[ 79 70 179]
[ 81 71 181]
[ 81 74 185]]]
[[162 162 162 ... 170 155 128]
[162 162 162 ... 170 155 128]
[162 162 162 ... 170 155 128]
...
[ 43 43 50 ... 104 100 98]
[ 44 44 55 ... 104 105 108]
[ 44 44 55 ... 104 105 108]]
Ndim of img(BGR): 3, gray: 2
Shape of img(BGR): (512, 512, 3), gray: (512, 512)
Size of img(BGR): 786432, gray: 262144
Dtype of img(BGR): uint8, gray: uint8
Dtype of imgFloat: float32
进程已结束,退出代码为 0
## 结果分析
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/2b9e0832b72b4f82a213821e5978c9c7.png)
对于这个数组,我们可以按照上图分析,注意第0列为BGR