简体   繁体   English

如何在python中除数并转换为整数?

[英]how to divide numbers in python and convert as integer?

Using given code, i am getting 0 0 0 0. Why answer become zero? 使用给定的代码,我得到0 0 00。为什么答案变成零? 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. 我正在尝试获取x,y坐标并想要裁剪图像,但看来除法不能正常工作。请向我建议一些想法以解决问题。

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)

If you're using Python 2 then you are doing integer division, not floating point one. 如果您使用的是Python 2,那么您正在执行整数除法,而不是浮点数一。 Try declaring width and height as floating point ( width = 400.0 , height = 800.0 ). 尝试将widthheight声明为浮点( width = 400.0height = 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 . 更新代码并使用浮点后:得到零,因为将小于1的正浮点数转换为整数时,得到0。例如int(0.5) == 0int(1.5) == 1 Basically, you throw away the fractional part. 基本上,您会舍弃小数部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM