如何在检测到的矩形中上下移动 cv2.line 以模拟 python 中的面部扫描?
Posted
技术标签:
【中文标题】如何在检测到的矩形中上下移动 cv2.line 以模拟 python 中的面部扫描?【英文标题】:How to move cv2.line up and down in detected rectangle to simulate face scanning in python? 【发布时间】:2020-01-14 15:51:22 【问题描述】:我需要在检测到的人脸矩形上上下移动一条线。看起来真实的面部正在扫描。我想使用 python 和 opencv 演示基于 GUI 的扫描。我已经尝试了以下
import cv2
img=cv2.imread("10.jpg")
cv2.rectangle(img, (60, 50), (140, 150), (255,0,0), 2)
cv2.line(img, (60,50),(150, 140), (0, 255, 0), thickness=3, lineType=8)
cv2.imshow("face",img)
k = cv2.waitKey(0)
【问题讨论】:
【参考方案1】:您可以尝试在循环中将线从起始位置移动到结束位置。 我会发布我的代码,但你必须针对你检测到的每一张脸进行调整。玩得开心!
import cv2
capture = cv2.VideoCapture(0)
#start position for y coordinate
start_y = 150
line_y = 150
#ending position for y coordinate
end_y = 50
#x position (bottom left and bottom right of the box)
x_left = 60
x_right = 140
#speed of scanning
speed = 3
#main loop
while True:
#read frame
ret, img=capture.read()
#create bounding box
cv2.rectangle(img, (60, 50), (140, 150), (255,0,0), 2)
#draw a line
cv2.line(img, (x_left,line_y),(x_right, line_y), (0, 255, 0), thickness=3, lineType=8)
#x always stays the same for the line but y decreases so the line goes up (in opencv y goes from up to down)
#speed makes the line go faster or slower (you can adjust it as you want)
line_y -= speed
#if the line gets to the top of the bounding box get the y value back to the bottom
#of the bounding box so the line goes back down
if line_y <= end_y:
line_y = start_y
#show image
cv2.imshow("face",img)
k = cv2.waitKey(10)
#if press ESC stop everything
if k == 27:
break
capture.release()
cv2.destroyAllWindows()
【讨论】:
【参考方案2】:您可以遍历矩形高度并在循环的每次迭代中绘制线条。要“向下扫描”,从[0 ... height]
迭代,要“向上扫描”,从[height ... 0]
反向迭代
import cv2
import numpy as np
height = 400
width = 400
image = np.zeros((width,height,3), dtype=np.uint8)
cv2.imshow('image', image)
cv2.waitKey(1000)
for line in range(height * 2):
image[:,:] = [0,0,0]
cv2.line(image, (0,line//2),(width, line//2), (36, 255, 12), thickness=2, lineType=8)
cv2.imshow('image', image)
cv2.waitKey(2)
for line in range(height * 2)[::-1]:
image[:,:] = [0,0,0]
cv2.line(image, (0,line//2),(width, line//2), (36, 255, 12), thickness=2, lineType=8)
cv2.imshow('image', image)
cv2.waitKey(2)
【讨论】:
你能帮我把这段代码转换成 wxpython 代码吗? @nathancy以上是关于如何在检测到的矩形中上下移动 cv2.line 以模拟 python 中的面部扫描?的主要内容,如果未能解决你的问题,请参考以下文章