OpenCV
imread的第二个参数:格式指定
- cv2.IMREAD_COLOR : 彩色图像(默认)
- cv2.IMREAD_GRAYSCALE : 灰度图像
import cv2 as cv
img = cv.imread('xxx\\name.jpg')
def show(name, img) # name - 窗口名, img - 图像
cv.imshow(name, img)
cv.waitKey(0)
cv.destroyAllWindows()
vc = cv.VideoCapture('xxx\\name.mp4')
# 用来判断图像是否正常读取
if vc.isOpened():
open, frame = vc. read() # read会返回两个, boolean, 帧
else :
open = False
while open:
ret, frame = vc.read()
if frame is None: # 没读完整,退出
break
if ret == True: # 读到,ret置true
gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY) # 转成灰度图像
cv.imshow('result', gray) # 显示每一帧
if cv.waitKey(100) & 0xFF == 27: # 控制帧率
break
vc.release() # 释放
cv.destroyAllWindows()
ROI(感兴趣区域)
img = cv.imread(name1)
cat = img[0:100, 0:200] # 切片操作
show('cat', cat)
OpenCV 图片存储,以B,G,R格式
b, g, r = cv.split(img) # 存储 B, G, R
b, g, r
print(b.shape)
img=cv.merge((b,g,r))
img.shape
cur_img=img.copy()
cur_img[:,:,0] = 0 # B通道置0
cur_img[:,:,1] = 0 # G通道置0
show('R', cur_img)
填充方式 (borderType):第五个参数
- BORDER_REPLICATE : 复制法,复制最边缘像素
- BORDER_REFLECT : 反射法,对感兴趣的图像中的像素在两边进行复制
- BORDER_REFLECT_101 : 反射法,以最边缘像素为轴对称
- BORDER_WRAP : 外包装法
- BORDER_CONSTANT : 常量法,常数值填充
top_size,bottom_size,left_size,right_size=(30,30,30,30) # 制定填充宽度
#
replicate=cv.copyMakeBorder(img, top_size,bottom_size,left_size,right_size,borderType=cv.BORDER_REPLICATE)
reflect=cv.copyMakeBorder(img, top_size,bottom_size,left_size,right_size,cv.BORDER_REFLECT)
reflect101=cv.copyMakeBorder(img, top_size,bottom_size,left_size,right_size,cv.BORDER_REFLECT_101)
wrap=cv.copyMakeBorder(img, top_size,bottom_size,left_size,right_size,cv.BORDER_WRAP)
constant=cv.copyMakeBorder(img, top_size,bottom_size,left_size,right_size,cv.BORDER_CONSTANT,value=0) # 常数填充,需指定value值
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()
name1 = name+'1.jpg'
name2 = name+'2.jpg'
img_cat1 = cv.imread(name1)
img_cat2 = cv.imread(name2)
img_cat2.resize((300,300,3)) # 同shape 才能执行运算
img_cat1[:5,:,0]
img_cat1_1 = img_cat1 + 10 # 加法会溢出 == %256
img_cat1_1[:5,:,0]
print((img_cat1 + img_cat2)[:5,:,0]) # 加法会溢出 == %256
print(cv.add(img_cat1, img_cat2)[:5,:,0]) # 不溢出
坐标都是,宽,高,不要写反了
img1 = cv.imread(name+'1.jpg')
img2 = cv.imread(name+'2.jpg')
img2 = cv.resize(img2, (300, 300))
img_new = cv.resize(img1, (200 , 100))
plt.imshow(img_new)
img_new = cv.resize(img1, (0, 0), fx=2,fy=3)
plt.imshow(img_new)
res = cv.addWeighted(img2, 0.4, img1, 0.6, 0)
plt.imshow(res)