Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

opencv using python - copy roi to new smaller image

Tags:

python

opencv

In opencv using python - How can I create a new image that is simply a copy of an roi from another image? Surely there is something along the lines of

Mat roi = img( Rect(x,y,w,h) );

for python, or anything more elegant than the brute force

rect=[x,y,w,h]
img = cv2.imread(subst)
roi= np.zeros((rect[3],rect[2],3),np.uint8)  #is this really reversed? who ordered that?
cv2.rectangle(img,(x,y),(w+x,h+y),[255,0,0],thickness=1)
cv2.imshow('img',img)
cv2.waitKey()
#cv.Copy(cv.fromarray(img),cv.fromarray(roi),cv.fromarray(mask))  #can't make it work...
for x in range(rect[2]):
    for y in range(rect[3]):
        roi[y,x,:]=img[y+rect[1],x+rect[0],:]

and btw how do the x,y coordinates order - is it [x,y,c] or [y,x,c] to specify a point at x (horizontal) and y (vertical)? It seems like its [y,x,c], iiuc, while the cv2.rectangle is (x,y) and img.shape is (y,x) which would be even more annoying than (g,r,b) instead of (r,g,b)....

like image 890
jeremy_rutman Avatar asked Oct 19 '25 08:10

jeremy_rutman


1 Answers

import os
import cv2

img = cv2.imread(filename)
roi = img[row:row+height,column:column+width]
cv2.imshow('ROI',roi)
cv2.waitKey(0)
like image 101
mcduffee Avatar answered Oct 21 '25 22:10

mcduffee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!