0

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)
shudheer
  • 25
  • 1
  • 6
  • Possible duplicate of [Why does Python return 0 for simple division calculation?](http://stackoverflow.com/questions/10768724/why-does-python-return-0-for-simple-division-calculation) – languitar Mar 02 '17 at 11:36
  • You didn't get `0, 0, 0, 0`, you got `1, 1, 0, 0`, right? If you give us bad data, we can't help. Beyond that, you explicitly converted to `int`, what exactly do you expect to get when you divide a number less than 800 by 800 and truncate? – ShadowRanger Mar 02 '17 at 11:37
  • @ShadowRanger see the correct data. – shudheer Mar 02 '17 at 11:42
  • I think you need to fix your maths rather than your code. Can you give examples of `first_corner` and `last_corner`? How are they expressed? In pixels, or as fractions? Either way, you probably don't want to be dividing by `float(w)` and `float(h)`; it's possible that you need to multiply instead. – Mark Dickinson Mar 02 '17 at 11:45
  • So why are you dividing at all? Surely you want to end up simply doing `img[425:587, 475:728]` (or similar)? – Mark Dickinson Mar 02 '17 at 12:53

1 Answers1

1

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.

lukeg
  • 4,189
  • 3
  • 19
  • 40
  • what is the solution as i have to use python 2.X version only? – shudheer Mar 02 '17 at 11:43
  • Why don't you show an [MCVE](https://stackoverflow.com/help/mcve) with concrete input and your desired output? Your question was actually better in this respect before the last edit, because there were actual specific numbers to discuss. – Useless Mar 02 '17 at 11:53