将float64类型的np.array转换为类型uint8缩放值 [英] Convert np.array of type float64 to type uint8 scaling values

查看:8473
本文介绍了将float64类型的np.array转换为类型uint8缩放值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的np.array 数据,它代表一个特定的灰度图像。
我需要使用SimpleBlobDetector(),遗憾的是只接受8bit图像,所以我需要转换这个图像,显然有质量损失。

I have a particular np.array data which represents a particular grayscale image. I need to use SimpleBlobDetector() that unfortunately only accepts 8bit images, so I need to convert this image, obviously having a quality-loss.

我'已经尝试过:

import numpy as np
import cv2
[...]
data = data / data.max() #normalizes data in range 0 - 255
data = 255 * data
img = data.astype(np.uint8)
cv2.imshow("Window", img)

但是 cv2.imshow 没有给出图像正如预期的那样,但有着奇怪的失真...

But cv2.imshow is not giving the image as expected, but with strange distortion...

最后,我只需要将np.float64转换为np.uint8,缩放所有值并截断其余值,例如。 65535变为255,65534变为254等等....任何帮助?

In the end, I only need to convert a np.float64 to np.uint8 scaling all the values and truncating the rest, eg. 65535 becomes 255, 65534 becomes 254 and so on.... Any help?

谢谢。

推荐答案

规范化图像的一种更好方法是取每个值并除以数据类型所经历的最大值。这样可以确保图像中动态范围较小的图像保持较小,并且不会无意中将其标准化,使其变为灰色。例如,如果您的图片的动态范围为 [0-2] ,那么现在的代码会将其缩放为强度为 [0, 128,255] 。转换为 np.uint8 后,您希望这些值保持较小。

A better way to normalize your image is to take each value and divide by the largest value experienced by the data type. This ensures that images that have a small dynamic range in your image remain small and they're not inadvertently normalized so that they become gray. For example, if your image had a dynamic range of [0-2], the code right now would scale that to have intensities of [0, 128, 255]. You want these to remain small after converting to np.uint8.

因此,将每个值除以图像类型可能的最大值,而不是实际图像本身。然后,您可以将其缩放255以生成标准化结果。使用 numpy.iinfo 并为其提供图像的类型( dtype ),您将获得该类型的信息结构。然后,您将从此结构中访问 max 字段以确定最大值。

Therefore, divide every value by the largest value possible by the image type, not the actual image itself. You would then scale this by 255 to produced the normalized result. Use numpy.iinfo and provide it the type (dtype) of the image and you will obtain a structure of information for that type. You would then access the max field from this structure to determine the maximum value.

因此,如上所述,请对您的代码进行以下修改:

So with the above, do the following modifications to your code:

import numpy as np
import cv2
[...]
info = np.iinfo(data.dtype) # Get the information of the incoming image type
data = data.astype(np.float64) / info.max # normalize the data to 0 - 1
data = 255 * data # Now scale by 255
img = data.astype(np.uint8)
cv2.imshow("Window", img)

请注意,我还要转换图像进入 np.float64 以防传入数据类型不是这样,并在进行除法时保持浮点精度。

Note that I've additionally converted the image into np.float64 in case the incoming data type is not so and to maintain floating-point precision when doing the division.

这篇关于将float64类型的np.array转换为类型uint8缩放值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆