读/写图像文件
opencv 具有 imread() 和 imwrite() 函数支持静态图像的文件读写 ,主要的文件格式 BMP、PNG、JPEG、TIFF
图像是由像素构成,像素的取值范围是0~255,每个像素由一个8位整数表示,所以是256
1.图像读写
import cv2
image=cv2.imread('0.jpg') #读取
cv2.imwrite('wukong.jpeg',image) #写入
cv2.imshow('wukong',image) #展示
cv2.waitKey() #展示时间
2.修改图片的像素值:
import cv2
# import numpy as np
img=cv2.imread('0.jpg')
px=img[0,0] #左上角
print('左上角原本像素值:',px)
blue=[255,0,0] #G B R
px=blue
print('修改后的像素值:',px)
左上角原本像素值: [45 40 37]
修改后的像素值: [255, 0, 0]
Process finished with exit code 0
能用矩阵操作,便用,使用numpy中的array.item()以及array.itemset()会加快速度,逐渐修改像素会慢
img = cv2.imread('0.jpg')
print(img.item(0,0,0)) #0行 0列 第0个通道
img.itemset((0,0,0),255) #转成255
print(img[0,0])
45
[255 40 37]
Process finished with exit code 0
3.图像属性: 行、列、通道、数据类型、像素数目
img = cv2.imread('0.jpg')
print(img.shape) #形状
print(img.size) #数目
print(img.dtype) #类型
(305, 522, 3)
477630
uint8
Process finished with exit code 0
4.图像ROI
对图像的特定区域操作。ROI是使用numpy索引来获得的。
例:选择球的部分并拷贝到其他区域
img = cv2.imread('cluo.jpg')
print(img.shape)
ball =img[600:700,380:480]
img[0:100,0:100]=ball
cv2.imshow('football',ball)
cv2.imwrite('zuqiu.jpeg',img)
cv2.waitKey()