显示线条的底部图像并使用“打开”剪切上部图像

2024-03-29 09:53:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我正试着斜切直播视频。在…的帮助下等高线,我已经提到了尺寸,我的目标是显示我画的线的下边的视频,上面的视频应该被裁剪, 作为一个初学者,我只能用下面的代码画一条线:

import cv2

cv2.namedWindow("preview")
vc = cv2.VideoCapture(0)

if vc.isOpened(): # try to get the first frame
    rval, frame = vc.read()
else:
    rval = False

while rval:
    cv2.imshow("preview", frame)
    rval, frame = vc.read()
    key = cv2.waitKey(20)
    if key == 27: # exit on ESC
        break
    else:
        cv2.line(img=frame, pt1=(700,5), pt2=(5, 450), color=(255, 0, 0), thickness=1, lineType=8, shift=0)

vc.release()
cv2.destroyWindow("preview")

输出: enter image description here

这方面的建议很有帮助


Tags: key代码目标read视频if尺寸preview
2条回答

要裁剪图像,我使用maskcv2.bitwise_and()。在

源图像:

source image

面具:

# Create a mask image with a triangle on it
y,x,_ = img.shape
mask = np.zeros((y,x), np.uint8)
triangle_cnt = np.array( [(x,y), (x,0), (0,y)] )
cv2.drawContours(mask, [triangle_cnt], 0, 255, -1)

mask image

输出:

^{pr2}$

output

下面的代码将屏蔽线上方的点。我在这里添加了评论,这样你就可以跟踪发生了什么。有更快的方法可以做到这一点,但我想要一些容易阅读的东西。在

import cv2
import matplotlib.pyplot as plt
import numpy as np

path = r"path\to\img"

img = cv2.imread(path)

#plt.imshow(img)
#plt.show()
pt1 = (86, 0) #ensure this point exists within the image
pt2 = (0, 101) #ensure this point exists within the image
cv2.line(img, pt1, pt2, (255, 255, 255))

#plt.imshow(img)
#plt.show()
#slope of line
m = float(pt2[1] - pt1[1])/float(pt2[0] - pt1[0])
c = pt1[1] - m*pt1[0]
#create mask image
mask1 = np.zeros(img.shape, np.uint8)
#for every point in the image
for x in np.arange(0, 87):
    for y in np.arange(0, 102):
        #test if point exists above the line, 
        if y > m*x + c:
            mask1[y][x] = (255, 255, 255)


#plt.imshow(mask1)
#plt.show()
fin_img = cv2.merge((img[:, :, 0], img[:, :, 1], img[:, :, 2], mask1[:,:, 0]))
#plt.imshow(fin_img)
#plt.show()

cv2.imwrite('output.png', fin_img)

相关问题 更多 >