1 year ago
#206846
Daniele Radaelli
How to extract an area of a video using coordinates from cv2.rectangle
I'm trying to write a code in Python that should read a video and at any time the user must be able to draw a rectangular area on it. After that I use the rectangle coordinates to extract the area selected from the current frame. This smaller area is called region in my code and running this code on spyder, this variable remains empty. I don't know why, since rect is composed of 4 integer numbers. Thank you in advance for your help.
import cv2
rect = (0,0,0,0)
startPoint = False
endPoint = False
selected_ROI = False
def on_mouse(event,x,y,flags,params):
global rect,startPoint,endPoint, selected_ROI
if event == cv2.EVENT_LBUTTONDOWN:
if startPoint == True and endPoint == True:
startPoint = False
endPoint = False
rect = (0, 0, 0, 0)
selected_ROI = False
if startPoint == False:
rect = (x, y, 0, 0)
startPoint = True
elif endPoint == False:
rect = (rect[0], rect[1], x, y)
endPoint = True
selected_ROI = True
video = cv2.VideoCapture('giri_motore.mkv')
while video.isOpened():
# Read frame
ret, frame = video.read()
cv2.namedWindow('original')
cv2.setMouseCallback('original', on_mouse)
if selected_ROI:
cv2.rectangle(frame, (rect[0], rect[1]), (rect[2], rect[3]), (255, 0, 255), 2)
region = frame[rect[0]:rect[1], rect[2]:rect[3]]
cv2.imshow('original', frame)
key = cv2.waitKey(1)
if key == ord('q'):
break
video.release()
cv2.destroyAllWindows()
opencv
video-capture
roi
drawrectangle
0 Answers
Your Answer