引入opencv
import cv2
读取图片:
img=cv2.imread('cat.jpg')
img=cv2.imread('cat.jpg',cv2.IMREAD_GRAYSCALE)
展示图片:
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.waitKey(10000)
cv2.destroyAllWindows()
读取图片的规格:
img.shape
该属性返回的结果为hwc(h:height长度,w:weight宽度,c:channel通道)如rgb图像为三通道图像c值为3。
保存图片:
#保存
cv2.imwrite('mycat.png',img)
显示读取图片读取格式:
type(img)
图片size属性:
img.size
图片dtype属性:
img.dtype
视频读取:
vc = cv2.VideoCapture('test.mp4')
if vc.isOpened():
oepn, frame = vc.read()
else:
open = False
对读取视频中的帧进行相应处理:
下面代码为将所有帧转换为灰度图形式。
while open:
ret, frame = vc.read()
if frame is None:
break
if ret == True:
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('result', gray)
if cv2.waitKey(100) & 0xFF == 27:
break
vc.release()
cv2.destroyAllWindows()
截取图像部分:
img=cv2.imread('cat.jpg')
cat=img[0:50,0:200]
cv_show('cat',cat)
颜色通道提取
cur_img = img.copy()
cur_img[:,:,0] = 0
cur_img[:,:,1] = 0
cv_show('R',cur_img)
cur_img = img.copy()
cur_img[:,:,0] = 0
cur_img[:,:,2] = 0
cv_show('G',cur_img)
cur_img = img.copy()
cur_img[:,:,1] = 0
cur_img[:,:,2] = 0
cv_show('B',cur_img)
将其他通道制0的方式实现颜色通道提取:
b,g,r=cv2.split(img)
颜色通道融合
img=cv2.merge((b,g,r))
边界填充:
top_size,bottom_size,left_size,right_size = (50,50,50,50)
replicate = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, borderType=cv2.BORDER_REPLICATE)
reflect = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size, cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img, top_size, bottom_size, left_size, right_size,cv2.BORDER_CONSTANT, value=0)
import matplotlib.pyplot as plt
plt.subplot(231), plt.imshow(img, '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()
对图片进行算数运算:
img_cat2= img_cat +10
img_cat[:5,:,0]
cv2.add(img_cat,img_cat2)[:5,:,0]
图像融合
两张图片要进行融合需要图片规格一致,对于规格不一致的图片需要用resize()方法调节规格。
img_dog = cv2.resize(img_dog, (500, 414))
img_dog.shape
res = cv2.resize(img, (0, 0), fx=4, fy=4)
res = cv2.addWeighted(img_cat, 0.4, img_dog, 0.6, 0)
|