Python 将图像从 CV_64F 转换为 CV_8U

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46260601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 17:32:54  来源:igfitidea点击:

convert image from CV_64F to CV_8U

pythonc++numpyopencv

提问by Jazz

I want to convert an image of type CV_64FC1to CV_8UC1in Python using OpenCV.

我想使用 OpenCV将类型的图像转换CV_64FC1CV_8UC1Python 中的图像。

In C++, using convertTofunction, we can easily convert image type using following code snippet:

在 C++ 中,使用convertTo函数,我们可以使用以下代码片段轻松转换图像类型:

image.convertTo(image, CV_8UC1);

I have searched on Internet but unable to find any solution without errors. Any function in Python OpenCV to convert this?

我在互联网上搜索过,但找不到任何没有错误的解决方案。Python OpenCV 中的任何函数来转换它?

回答by frogatto

You can convert it to a Numpy array.

您可以将其转换为 Numpy 数组。

import numpy as np

# Convert source image to unsigned 8 bit integer Numpy array
arr = np.uint8(image)

# Width and height
h, w = arr.shape

It seems OpenCV Python APIs accept Numpy arrays as well. I've not tested it though. Please test it and let me know the result.

似乎 OpenCV Python API 也接受 Numpy 数组。不过我还没有测试过。请测试一下,让我知道结果。

回答by Prathap Narayanappa

I faced similar issue and when I trying to convert the image 64F to CV_U8 I would end up with a black screen.

我遇到了类似的问题,当我尝试将图像 64F 转换为 CV_U8 时,我最终会出现黑屏。

This linkwill help you understand the datatypes and conversion. Below is the code that worked for me.

链接将帮助您了解数据类型和转换。下面是对我有用的代码。

from skimage import img_as_ubyte
cv_image = img_as_ubyte(any_skimage_image)

回答by Ani Aggarwal

For those getting a black screen or lots of noise, you'll want to normalize your image first before converting to 8-bit. This is done with numpy directly as OpenCV uses numpy arrays for its images.

对于那些出现黑屏或大量噪点的人,您需要先对图像进行标准化,然后再转换为 8 位。这是直接使用 numpy 完成的,因为 OpenCV 对其图像使用 numpy 数组。

Before normalization, the image's range is from 4267.0to -4407.0in my case. Now to normalize:

在规范化之前,图像的范围是从4267.0-4407.0在我的情况下。现在规范化:

# img is a numpy array/cv2 image
img = img - img.min() # Now between 0 and 8674
img = img / img.max() * 255

Now that the image is between 0 and 255, we can convert to a 8-bit integer.

现在图像在 0 到 255 之间,我们可以转换为 8 位整数。

new_img = np.uint8(img)

This can also be done by img.astype(np.uint8).

这也可以通过img.astype(np.uint8).