【问题标题】:Display the bottom image of the line and cut the upper image using Opencv显示线条的底部图像并使用Opencv剪切上部图像
【发布时间】:2019-04-26 07:12:40
【问题描述】:

我正在尝试对角裁剪实时视频。在 cv.line 的帮助下,我已经提到了尺寸,我的目标是显示我绘制的线下侧的视频,并且应该裁剪上视频, 作为初学者,我只能使用以下代码画一条线:

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")

输出:

对此的建议将非常有帮助

【问题讨论】:

  • 没有任何软件可以处理三角形或非矩形图像。您需要使左上角透明(或纯黑色或纯白色)而不是裁剪。
  • 你能分享一下帮助我使左上角透明的代码吗?
  • 在此之前,请注意 AFAIK,imshow() 不处理透明度,但您保存的任何 PNG 文件都将遵循透明度。
  • 要增加透明度,请使用RGBAframe = cv2.cvtColor(frame, cv2.COLOR_RGB2RGBA),然后在RGBAframe[:,:,3]中的黑色背景上绘制一个白色三角形
  • 这里绘制实心三角形的代码...stackoverflow.com/a/51876455/2836621

标签: python python-3.x opencv


【解决方案1】:

下面的代码将掩盖线上方的点。我在此处添加了 cmets,以便您可以了解正在发生的事情。有更快的方法可以做到这一点,但我想要一些易于阅读的东西。

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)

【讨论】:

  • 请注意:OpenCV 中的 for 循环是一种非常低效的操作。 100*100 左右的图像也可以,但除此之外,我强烈建议使用 opencv 函数而不是 for 循环。
【解决方案2】:

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

源图片:

面具:

# 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)

输出:

img = cv2.bitwise_and(img, img, mask=mask)

【讨论】:

    猜你喜欢
    • 2016-07-18
    • 1970-01-01
    • 1970-01-01
    • 2018-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    相关资源
    最近更新 更多