简体   繁体   English

Python / Opencv Float在转换时转换为不正确的Int

[英]Python/Opencv Float converting to incorrect Int when casted

I am using OpenCV + Python to add an overlay image on a few videos automatically. 我正在使用OpenCV + Python自动在几个视频上添加叠加图像。 For the most part my code works fine, except with collecting some heuristics from a given input video. 在大多数情况下,我的代码工作正常,除了从给定的输入视频中收集一些启发式方法。 I collect the number of frames and the FPS of the video using the OpenCV VideoCapture.Get() function and store then to variables respectively. 我使用OpenCV VideoCapture.Get()函数收集视频的帧数和FPS,然后分别存储到变量。 The resulting numeric are float values which I then cast to int , but here lies the problem: the values drop by one! 结果数字是float值,然后我将其转换为int ,但这里存在问题:值减1!

The full code snippet here: 这里的完整代码段:

import cv2 as cv

inputnm = "testVideo.mp4"

# Load the video into memory
camera = cv.VideoCapture(inputnm)

# Get important heuristics
fps = camera.get(cv.CAP_PROP_FPS)
maxFrames = camera.get(cv.CAP_PROP_FRAME_COUNT)

print type(fps), type(maxFrames)
print fps,maxFrames
print int(fps), int(maxFrames)
quit()

This produces the output: 这会产生输出:

<type 'float'> <type 'float'>
60.0 401.0
59 400

Can anyone explain this to me why? 任何人都可以向我解释这个原因吗? I have tried converting it to numpy.float128 and then to numpy.unit8 but it still drops the values down by one. 我已经尝试将它转换为numpy.float128然后转换为numpy.unit8但它仍然将值降低一个。 Strange. 奇怪。

You have just seen the wonders of the floating point. 你刚刚看到了浮点的奇迹。

Python shows numbers as a close precision to their conversation from floating point, which is usually precise enough for visualization and in many cases also for computation, but in cases like yours the precision is simply not enough. Python将数字显示为从浮点开始的对话的精确度,这通常对于可视化而言足够精确,在很多情况下也用于计算,但在像你这样的情况下,精度是不够的。

Use round(maxFrames) . 使用round(maxFrames)

Essentially what is happening is your floating point variable is displaying as 60, but in reality it is probably 59 and some change. 基本上发生的事情是你的浮点变量显示为60,但实际上它可能是59并且有些变化。 It will not display as 59 because python is smart enough to round up for our sake, (59.99999.. = 60). 它不会显示为59,因为python足够聪明,为了我们的缘故(59.99999 .. = 60)。 When you cast to int, you're truncating the decimals off of 59 which seems to drop the value by 1 (59.9999 => 59). 当你转换为int时,你将截断59的小数,这似乎会使值减1(59.9999 => 59)。

Edit: like the other user suggested, round(maxFrames) will round the value to the nearest whole number. 编辑:与其他用户建议的一样, round(maxFrames)会将值四舍五入到最接近的整数。 Then you can cast to int and get the right result. 然后你可以转换为int并获得正确的结果。

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

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