jeremy_rutman
jeremy_rutman

Reputation: 5720

opencv using python - copy roi to new smaller image

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

Upvotes: 4

Views: 16254

Answers (1)

mcduffee
mcduffee

Reputation: 1257

import os
import cv2

img = cv2.imread(filename)
roi = img[row:row+height,column:column+width]
cv2.imshow('ROI',roi)
cv2.waitKey(0)

Upvotes: 6

Related Questions