Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect movement within a specific area with Python Opencv?

Currently I have an algorithm using Python and OpenCV that detects geometrical shapes and calculates its length (without accuracy).

But I need to make that detection within a specific area, in this case it would be inside a rectangle that I draw with the cv2.rect function but I have no idea how to do it and I couldn't find any information on how to do it on the internet.

I am using python 3.7 and OpenCV 3

Can someone help me?

description of what I want to achieve

like image 413
miqi666 Avatar asked Mar 06 '26 14:03

miqi666


2 Answers

Since images are really just arrays, you can directly select a region of interest using slices, like this:

import cv2
frame = cv2.imread(image)

use_this_smaller_frame = frame[50:100, 300:600] 

This will select a region of y ranging from 50 to 100, and x from 300 to 600, giving you a smaller image that is just the part you care about. Note image indexing is [y, x] and not [x, y] as you might expect.

Use the coordinates you use to draw the rectangle to slice the image, then do the rest of your processing on just the smaller image.

like image 197
Matthew Salvatore Viglione Avatar answered Mar 08 '26 04:03

Matthew Salvatore Viglione


Since you are using Python, you can simply slice the image on the rectangle.

x, y, w, h = cv2.selectROI(window_name, image)  # or something
img_cropped = img[y:y+h, x:x+h] 

You can also check out this tutorial

like image 44
Andreas Avatar answered Mar 08 '26 04:03

Andreas