shudheer
shudheer

Reputation: 25

how to divide numbers in python and convert as integer?

Using given code, i am getting 0 0 0 0. Why answer become zero? I am trying to get x,y coordinates and want to crop image but it seems division is not working properly.Please suggest me some idea to sort it out.

def ROI_extract(first_corner,last_corner,image):
    img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    w,h = img.shape[::-1]
    Xtf = int(first_corner[0] / float(w))
    Xbf = int(last_corner[0] / float(w))
    Ytf = int(first_corner[1]/  float(h))
    Ybf = int(last_corner[1]/  float(h))
    print Xtf,Xbf,Ytf,Ybf
    ROI_img = image[Ytf[1]:Ybf[1],Xtf[0]:Xbf[0]] 
    cv2.imwrite('cropped', ROI_img)
    return ROI_img

image = cv2.imread('sample.jpg')
first = [475,425]
last = [728,587]
img =  ROI_extract(first, last, image)

Upvotes: 0

Views: 2993

Answers (1)

lukeg
lukeg

Reputation: 4399

If you're using Python 2 then you are doing integer division, not floating point one. Try declaring width and height as floating point (width = 400.0, height = 800.0).

UPDATE

After you've updated the code and used floating point: you get zeros, because when you convert a positive floating number that is less than one to an integer, you get 0. For example int(0.5) == 0 and int(1.5) == 1. Basically, you throw away the fractional part.

Upvotes: 1

Related Questions