二 OpenCV 图像的基础操作
1·获取像素并修改
import cv2 as cv import numpy as np img = cv.imread('E:\\fruits.jpg') ##print(img) px = img[100,100]#获取第100行第100列的3维矩阵 print(px) print(img[100,100,2])#获取矩阵值 val =[ i for i in img[100,100] ]#遍历矩阵 print(val)
print(img.item(100,100,2))#快速获取矩阵值 img.itemset((100,100,2),99)#快速修改矩阵值 print(img[100,100])
|
2·获取图像的属性信息
获取到属性信息有:
import cv2 as cv import numpy as np
img = cv.imread('E:\\fruits.jpg') print(img.shape) |
3·图像通道的合并和拆分
#局部区域赋值
import cv2 as cv import numpy as np #deal img = cv.imread('E:\\fruits.jpg') print(img.shape) area = img[280:340,330:390]#选中区域280行-340行,330列-360列 img[273:333,100:160] = area#将该区域修改值 #show cv.namedWindow('IMG') cv.imshow('IMG',img) cv.waitKey(0) cv.destroyAllWindows() |
![]()
|
#通道合并、拆分、修改
import cv2 as cv import numpy as np #deal img = cv.imread('E:\\fruits.jpg')
b,g,r = cv.split(img)#分离 img = cv.merge([b,g,r])#合并 #for i in img[:,:,0]:print(i)
img[:,:,0] = 0 #改变R通道值 img[:,:,1] = 0 #改变G通道值 img[:,:,2] = 0 #改变B通道值
#show cv.namedWindow('IMG') cv.imshow('IMG',img) cv.waitKey(0) cv.destroyAllWindows() |
4·图形填充
函数:cv.copyMakeBorder()
例子:略
- ·图像的算术运算
两个图形的大小,数据类型一致才可以进行运算,运算结果越界则取余数
#直接运算
例:
import cv2 as cv import numpy as np
x = np.uint8([250]) y = np.uint8([10]) z = np.uint16(65537)
print(cv.add(x,y))# 250+10 = 260 => 255 print(x+y)# 250+10 = 260 % 256 = 4 print(z)#65537%2^16 = 1 |
#图形混合:
算法一 :cv.addWeighted() g (x) = (1 − α) (x) + α (x) 其中α为透明度
例如:
import cv2 as cv import numpy as np #两个大小、数据类型一致的图像 imgf1 = cv.imread('E:\\fruits.jpg') imgf2 = cv.imread('E:\\fruits_copy.jpg')
dst = cv.addWeighted(imgf1,0.3,imgf2,0.7,0)#目标图像
cv.namedWindow('IMG') cv.imshow('IMG',dst) cv.waitKey(0) cv.destroyAllWindows()
|
#图形合并:在图片上加图标、水印、文字等
import cv2 as cv import numpy as np #两个大小、数据类型一致的图像 img1 = cv.imread('E:\\fruits.jpg') img2 = cv.imread('E:\\logo.jpg')
rows,cols ,channels = img2.shape roi = img1[0:rows,0:cols] img2gray = cv.cvtColor(img2,cv.COLOR_BGR2GRAY) ret,mask = cv.threshold(img2gray,175,255,cv.THRESH_BINARY)#峰值,掩码 mask_inv = cv.bitwise_not(mask)#按位not操作
img1_bg = cv.bitwise_and(roi,roi,mask) img2_fg = cv.bitwise_and(img2,img2,mask=mask_inv)
dst = cv.add(img1_bg,img2_fg) img1[0:rows,0:cols] = dst
cv.namedWindow('IMG') cv.imshow('IMG', img1) cv.waitKey(0) cv.destroyAllWindows()
|
![]()
|
参考 OpenCv官方教材文档