opencv 图像基本操作
目录:读取图像,获取属性信息,图像ROI,图像通道的拆分和合并
1. 读取图像
像素值返回:直接使用坐标即可获得, 修改像素值:直接通过坐标进行赋值
能用矩阵操作,便用,使用numpy中的array.item()以及array.itemset()会加快速度,逐渐修改像素会慢
import cv2 import numpy as np img = cv2.imread("test.jpg") #获取像素值 px = img[100,100] blue = img[100,100,0] print(px, blue) #修改像素值 img[100,100] = [255,255,255] print(img[100,100]) #使用item print(img.item(10,10,2)) img.itemset((10,10,2),100) print(img.item(10,10,2))
2. 图像属性: 行、列、通道、数据类型、像素数目
print(img.shape) #(342,548,3) (342,548) 图像是灰度时,只有行和列 print(img.size, img.dtype) #562248 uint8 图像像素数目, 图像数据类型, 注意:运行代码时数据类型是否一致
3. 图像ROI
ROI = img[y1:y2,x1:x2]
4. 拆分以及合并图像通道
b,g,r = cv2.split(img) img = cv2.merge(bgr) b = img[:,:,0] #修改时能尽量用numpy索引就用,用split比较耗时
5. 图像加法及混合
cv2.add(x, y) cv2.addWeighted(img1, 0.7, img2, 0.3, 0) #dst = a* img1 + b*img2 + c
6. 图像掩码
import cv2 import numpy as np # Load two images img1 = cv2.imread('messi5.jpg') img2 = cv2.imread('opencv-logo-white.png') # I want to put logo on top-left corner, So I create a ROI rows,cols,channels = img2.shape roi = img1[0:rows, 0:cols ] # Now create a mask of logo and create its inverse mask also img2gray = cv2.cvtColor(img2,cv2.COLOR_BGR2GRAY) ret, mask = cv2.threshold(img2gray, 10, 255, cv2.THRESH_BINARY) mask_inv = cv2.bitwise_not(mask) # Now black-out the area of logo in ROI img1_bg = cv2.bitwise_and(roi,roi,mask = mask_inv) # Take only region of logo from logo image. img2_fg = cv2.bitwise_and(img2,img2,mask = mask) # Put logo in ROI and modify the main image dst = cv2.add(img1_bg,img2_fg) img1[0:rows, 0:cols ] = dst cv2.imshow('res',img1) cv2.waitKey(0) cv2.destroyAllWindows()