图像的基础操作
获取像素值并修改
获取图像的属性
图像的ROI()
图像通道的拆分与合并
# -*- coding: utf-8 -*-
import cv2.cv2 as cv2
import numpy as np
import matplotlib.pyplot as plt
#获取并修改像素值
img = cv2.imread('namei.jpeg')
m = img.item(100,100,2)
print(m)
img.itemset((100, 100, 2), 100)
m = img.item(100,100,2)
print(m)
#获取图像属性
# img.size 可以返回图像的像素数目:
# img.shape 可以获取图像的形状。他的返回值是一个包含行数,列数,通道数的元组
# img.dtype 返回的是图像的数据类型.
img = cv2.imread('namei.jpeg')
# cv2.imshow('img', img)
print('image.shape:', img.shape)
print('image.size:', img.size)
print('image.dtype:', img.dtype)
img = cv2.imread('namei.jpeg')
# cv2.imshow('img_gray', img)
print(img.shape)
# 图像ROI
face = img[120:320, 200:400]
img[380:580, 450:650] = face
# cv2.imshow('img2', img)
# 拆分及合并图像通道
img = cv2.imread('namei.jpeg')
b, g, r = cv2.split(img)
img = cv2.merge([b,g,r])
cv2.imshow('R', r)
cv2.imshow('G', g)
cv2.imshow('B', b)
img = cv2.merge((b,g,r))
img[:,:,2] = 0
cv2.imshow('img_r0', img)
img = cv2.merge((b,g,r))
img[:,:,1] = 0
cv2.imshow('img_g0', img)
img = cv2.merge((b,g,r))
img[:,:,0] = 0
cv2.imshow('img_b0', img)
zeros = np.zeros(img.shape[:2], dtype = "uint8")
img = cv2.merge([b,zeros,zeros])
cv2.imshow('img_gr0', img)
img = cv2.merge([zeros,g,zeros])
cv2.imshow('img_br0', img)
img = cv2.merge([zeros,zeros,r])
cv2.imshow('img_bg0', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
#为图像扩边(填充)
import cv2
import numpy as np
from matplotlib import pyplot as plt
BLUE=[255,0,0]
img1=cv2.imread('namei.jpeg')
replicate = cv2.copyMakeBorder(img1,100,100,100,100,cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img1,100,100,100,100,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img1,100,100,100,100,cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img1,100,100,100,100,cv2.BORDER_WRAP)
constant= cv2.copyMakeBorder(img1,100,100,100,100,cv2.BORDER_CONSTANT,value=BLUE)
plt.subplot(231),plt.imshow(img1,'gray'),plt.title('ORIGINAL')
plt.subplot(232),plt.imshow(replicate,'gray'),plt.title('REPLICATE')
plt.subplot(233),plt.imshow(reflect,'gray'),plt.title('REFLECT')
plt.subplot(234),plt.imshow(reflect101,'gray'),plt.title('REFLECT_101')
plt.subplot(235),plt.imshow(wrap,'gray'),plt.title('WRAP')
plt.subplot(236),plt.imshow(constant,'gray'),plt.title('CONSTANT')
plt.show()
image.png
网友评论