Ask Your Question
1

Python crop not working

asked 2013-06-05 07:33:21 -0600

Rohan12111 gravatar image

Hello, I am relatively new to OpenCV. I have gleaned from tutorials and such that you can crop by using this script:

import cv2
import numpy as np
import video

cam = cv2.VideoCapture(0)
ret,vis = cam.read()    
crop = vis[100:400, 100:300]    
cv2.imshow("Img",vis)
cv2.imshow("Crop",crop)    
cv2.waitKey(0)

And this works fine. I get no errors.

However, when i put it into my main script, it doesn't work, i've narrowed it down to this section of code:

def PicTake(self):
    ret,vis = self.cam.read()
    x1,y1 = self.selection[0]
    x2,y2 = self.selection[1]
    a = 0
    taken = 0
    while taken == 0:
        if cv2.imread("C:\Python27\opencv\samples\python2\Major\Test"+str(a)+".png") == None:
            crop = vis[x1:y1, x2:y2]
            print crop
            cv2.imshow("crop",crop)
            cv2.imwrite("C:\Python27\opencv\samples\python2\Major\Test"+str(a)+".png",crop)
            taken = 1
        else:
            a+=1
    return ("Picture Taken")

where self.selection is just a list of two tuples [(x1,y1),(x2,y2)]. After the first if statement, print crop returns "[]" and empty list.

So yeah, why does it work with numbers and other situations fine, but not here?!

Any help is greatly appreciated, thanks!

edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
2

answered 2013-06-07 04:15:25 -0600

DanMaynard gravatar image

I assume that you would like to crop out a rectangle where the tuples (x1,y1) and (x2,y2) define the corners? Also to be clear, I assume origin at top left, x across and y down.

The [] notation is really array slicing in numpy and not an OpenCV function, so the first pair is rows and the second pair columns. This means you need

crop = vis[y1:y2, x1:x2]

Numpy slicing is very flexible, in general with 'basic slicing' like this it returns a view to the same memory buffer so if you modify crop the values in vis will change. This is probably not a problem here, but if it is you can force a copy easily with

crop = vis[y1:y2, x1:x2].copy()

... although obviously this is slightly slower to run.

edit flag offensive delete link more

Comments

How would you crop multiple ROIs from a np.array? With the coords arranged this way. Rect=([x1,y1,x2,y2],[x1,y1,x2,y2]...[n]).

Firelife gravatar imageFirelife ( 2019-01-30 07:29:31 -0600 )edit

Question Tools

Stats

Asked: 2013-06-05 07:33:21 -0600

Seen: 12,982 times

Last updated: Jun 07 '13