Rohan Williams
Rohan Williams

Reputation: 33

Python opencv crop not working

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!

Upvotes: 0

Views: 7601

Answers (3)

MountainLogic
MountainLogic

Reputation: 308

Croping can be very confusing. The CV world runs on corner pairs (X1,Y1), while python is working by slicing arrays. A correct cropping might look like:

crop = original[y1:y2, x1:x2] # pay attention to your Y's and X's

Upvotes: 0

samkhan13
samkhan13

Reputation: 3385

you need to use

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

see this answer to get a detailed explanation.

also check to see if the camera actually outputted anything. after the line

ret, vis = self.cam.read()

add these lines

if not ret:
 print 'No captured images'

Upvotes: 1

Kamyar Infinity
Kamyar Infinity

Reputation: 2759

vis is just a numpy array.
Check the result of print vis.shape to check the dimensions of your input image.
In case of a color image this would be something like this:

(367, 550, 3)

Which represents the dimensions in the order of height, width and then color depth.
So, if you want to select a portion from (x1,y1) to (x2,y2) when x2>x1 and y2>y1:

vis[y1:y2, x1:x2]

and this would also cover the depth dimension too.
Note that if y2<y1 or x2<x1, the result would be an empty array.

Upvotes: 4

Related Questions