1.访问和修改像素值
有两种方法,代码示例:
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\dell\\Desktop\\prac files\\prac.jpg')
print(img[100,100])
print(img[100,100,2])
img[100,100,2] = 150
print(img[100,100,2])
print(img.item(100,100,2))
img.itemset((100,100,2),255)
print(img.item(100,100,2))
2.访问图像属性
有三种属性,代码示例:
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\dell\\Desktop\\prac files\\prac.jpg')
print(img.shape)
print(img.size)
print(img.dtype)
3.图像的分割及复制
将图像的一部分进行分割,并将其复制到指定的位置,代码示例:
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\dell\\Desktop\\prac files\\prac.jpg')
half = img[0:1080, 0:960]
img[0:1080, 960:1920] = half
cv.imwrite('change.jpg', img)
4.拆分及合并图像通道
将BGR图像的B、G、R三通道进行分割存储,再合并成RGB图像格式,代码示例:
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\dell\\Desktop\\prac files\\prac.jpg')
b, g ,r = cv.split(img)
img2 = cv.merge([r, g, b])
b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]
img3 = cv.merge([r, g, b])
5.为图像添加边框
主要使用cv.copyMakeBorder()函数,此函数有以下参数: ①输入图像 ②上边框宽度 ③下边框宽度 ④左边框宽度 ⑤右边框宽度 ⑥边框类型,包括5种:
- cv.BORDER_CONSTANT
添加恒定的彩色边框。该值应作为下一个参数给出。 - cv.BORDER_REFLECT
边框将是边框元素的镜像,如下所示: fedcba | abcdefgh | hgfedcb - cv.BORDER_REFLECT_101或cv.BORDER_DEFAULT
例如: gfedcb | abcdefgh | gfedcba - cv.BORDER_REPLICATE
最后一个元素被复制,例如: aaaaaa | abcdefgh | hhhhhhh - cv.BORDER_WRAP
例如: cdefgh | abcdefgh | abcdefg
⑦value -边框的颜色(边框类型为cv.BORDER_CONSTANT)
代码示例:
import numpy as np
import cv2 as cv
img = cv.imread('C:\\Users\\dell\\Desktop\\prac files\\prac.jpg')
img1 = cv.cvtColor(img, cv.COLOR_BGR2RGB)
replicate = cv.copyMakeBorder(img1, 100, 100, 100, 100, cv.BORDER_REPLICATE)
reflect = cv.copyMakeBorder(img1, 100, 100, 100, 100, cv.BORDER_REFLECT)
reflect101 = cv.copyMakeBorder(img1, 100, 100, 100, 100,cv.BORDER_REFLECT_101)
wrap = cv.copyMakeBorder(img1, 100, 100, 100, 100, cv.BORDER_WRAP)
constant = cv.copyMakeBorder(img1, 100, 100, 100, 100, cv.BORDER_CONSTANT,(255,0,0))
plt.subplot(2, 3, 1)
plt.title('ORIGINAL')
plt.imshow(img1)
plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 2)
plt.title('REPLICATE')
plt.imshow(replicate)
plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 3)
plt.title('REFLECT')
plt.imshow(reflect)
plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 4)
plt.title('REFLECT_101')
plt.imshow(reflect101)
plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 5)
plt.title('WRAP')
plt.imshow(wrap)
plt.xticks([]), plt.yticks([])
plt.subplot(2, 3, 6)
plt.title('CONSTANT')
plt.imshow(constant)
plt.xticks([]), plt.yticks([])
plt.show()
|