如何在检测到的矩形中上下移动cv2.line来模拟python中的人脸扫描?

How to move cv2.line up and down in detected rectangle to simulate face scanning in python?

我需要在检测到的人脸矩形上上下移动一条线。看起来像是在扫描真人脸。我想使用 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)

您可以尝试将线从起始位置循环移动到结束位置。
我会 post 我的代码,但你必须为你检测到的每张脸调整它。玩得开心!

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

您可以遍历矩形高度并在循环的每次迭代中画线。到 "scan down",从 [0 ... height] 迭代到 "scan up",从 [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)