OpenCv基础_一

  • 图片的读取和展示
import cv2
img = cv2.imread('1.jpg')
cv2.imshow('img',img)
cv2.waitKey(0)
cv2.destroyAllWindows()

其中cv2.waitKey(0)代表图片的停留时间,0:表示手动关闭。cv2.waitKey(1000)表示过1000ms自动关闭

把展示定义为方法,方便使用

def cv_show(name,img):
    cv2.imshow(name,img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
  • 视频的读取和展示
vc = cv2.VideoCapture('test.mp4')
if vc.isOpened():
    open,frame = vc.read()
else:
    open = False
while open:
    open,res = vc.read()
    if res is None:
        break
    else:
        gray = cv2.cvtColor(res,cv2.COLOR_BGR2GRAY)
        cv2.imshow('res',gray)
        if cv2.waitKey(10) & 0xFF == 27:
            break

其中cv2.cvtColor()是对图像进行色彩空间的转换函数,利用cv2.COLOR_BGR2GRAY得到灰度图gray

  • 图片切片

  和数组,列表切片类似

img = cv2.imread("1.jpg")
cat = img[0:50,20:70]
cv_show("cat",cat)
  • 提取颜色通道

    1.利用split函数

img = cv2.imread('1.jpg')
b,g,r = cv2.split(img)

    2.利用shape的第三个值

img = cv2.imread("1.jpg")
r = img[:,:,0]
g = img[:,:,1]
b = img[:,:,2]

    改变颜色

#复制一个img2副本
img2 = cv2.copy(img)
#蓝色通道置为0
img2[:,:,0] = 0
#绿色通道置为0
img2[:,:,1] = 0
#只剩红色通道的图片
cv_show('img2',img2)
  • 边界填充

    BORDER_REPLICATE:复制法,即复制最边缘的像素。例如:aaaa|abcdefg|ggggg

    BORDER_REFLECT:反射法,即以最边缘的像素为对称轴。例如:fedcba|abcdefg|gfedec

    BORDER_REFLECT_101:反射法,也是最边缘的像素为对称轴,但与BORDER_REFLECT有区别。例如:   fedcb|abcdefg|fedec

    BORDER_WRAP:外包装法,即以图像的左边界与右边界相连,上下边界相连。例如:cdefgh|abcdefgh|abcdefg

    BORDER_CONSTANT:常量法。

img = cv2.imread('D:\Python\Pic\dog.jpg')
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)
replicate = cv2.cvtColor(replicate,cv2.COLOR_BGR2GRAY)
reflect = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REFLECT)
reflect101 = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_REFLECT_101)
wrap = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_WRAP)
constant = cv2.copyMakeBorder(img,top_size,bottom_size,left_size,right_size,borderType=cv2.BORDER_CONSTANT,value = 0)

#cv2是bgr,plt是rgb,调整以便让plt显示img原图
b,g,r = cv2.split(img)
img = cv2.merge((r,g,b))

plt.subplot(231),plt.imshow(img),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),plt.title('reflect101')
plt.subplot(235),plt.imshow(wrap),plt.title('wrap')
plt.subplot(236),plt.imshow(constant),plt.title('constant')

plt.show()

  •  图像融合

  把两张图片进行融合,由于两张图片shape不同,先cv2.resize()重置其中一张图片的shape,使得两张图片有相同的shape,再利用cv2.addWeighted进行融合

img1 = cv2.imread('1.jpg')
img2 = cv2.imread('test.jpg')
a,b,c = img1.shape
print(img1.shape)
img2 = cv2.resize(img2,(b,a))
print(img2.shape)
res = cv2.addWeighted(img1,0.6,img2,0.4,0)
cv_show('res',res)

 

posted @ 2021-02-04 11:44  MMMMinoz  阅读(95)  评论(0编辑  收藏  举报