opencv学习——图像的基本操作
导入库
import cv2
import matplotlib.pyplot as plt
图像和视频的读取(imread,imshow,VideoCature)
img = cv2.imread('cat.jpg')
def cv_show(name,img):
cv2.imshow(name,img)
cv2.waitKey(0)
cv2.destroyAllWindows()
print(img.shape)
print(img.dtype)
print(img.size)
cv2.imwrite("mycat.png",img)
video = cv2.VideoCapture("test.mp4")
while(video.read()):
ret, image = video.read()
cv2.namedWindow("video",0)
cv2.resizeWindow("video",420,300)
if ret == True:
gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
cv2.imshow("video",gray)
else:
break
key = cv2.waitKey(10)
if key == 27:
break
video.release()
cv2.destroyAllWindows()
![在这里插入图片描述](https://img-blog.csdnimg.cn/d1ccd2df3268410684a8a193a5dd9581.png#pic_center)
## 图像的截取
```python
img=cv2.imread('cat.jpg')
cat=img[0:50,0:200]#设置数组切片
cv_show('cat',cat)
颜色通道提取
b,g,r = cv2.split(img)
img = cv2.merge((b,g,r))
cur_img = img.copy()
cur_img[:,:,0] = 0
cur_img[:,:,1] = 0
cv_show("R",cur_img)
边界填充
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,borderType=cv2.BORDER_REPLICATE)
reflect101 = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REPLICATE)
wrap = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REPLICATE)
constant = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REPLICATE)
plt.subplot(231),plt.imshow(replicate,"gray"),plt.title("replicate")
plt.subplot(232),plt.imshow(reflect,"gray"),plt.title("reflect")
plt.subplot(233),plt.imshow(reflect101,"gray"),plt.title("reflect101")
plt.subplot(234),plt.imshow(wrap,"gray"),plt.title("wrap")
plt.subplot(235),plt.imshow(constant,"gray"),plt.title("constant")
plt.show()
数值运算
imgcat = img+10
imh = cv2.add(imgcat,img)
图像融合
imh = cv2.resize(img,(500,414))
res = cv2.addWeighted(img,0.4,imh,0.6,0,dst=None,dtype=-1)
res = cv2.resize(img ,(0,0),fx=5,fy=5)