2017-09-17 258 views
0

我想在Python中使用OpenCV将CV_64FC1类型的图像转换为CV_8UC1将图像从CV_64F转换为CV_8U

在C++中,使用convertTo功能,我们可以使用下面的代码片段很容易地转换图像类型:

image.convertTo(image, CV_8UC1); 

我已经搜索在互联网上,但无法找到没有错误的任何解决方案。 Python OpenCV中的任何函数将其转换?

+0

你看过[''cv2.cvtColor'](http://docs.opencv.org/2.4/modules/imgproc/doc/miscellaneous_transformations.html)吗? –

+0

我认为cv2.cvtColor用于颜色空间转换。我也可以使用它来转换图像类型吗? – Jazz

+0

[numpy uint8像素包装解决方案]的可能重复(https://stackoverflow.com/questions/7547557/numpy-uint8-pixel-wrapping-solution) – rayryeng

回答

2

您可以将其转换为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 

看来OpenCV Python API也接受Numpy数组。我还没有测试过它。请测试它并让我知道结果。

+0

我正在使用Python 3.6.2的OpenCV 3.2,同时运行代码,我得到这个错误:AttributeError:module'cv2'没有属性'fromarray'。 – Jazz

+0

@Jazz从OpenCV 3.2开始,似乎并不需要fromarray。 https://stackoverflow.com/questions/43923669/what-is-the-replacement-of-cv2-cv-fromarray-in-opencv-3-2 –

+1

在Python中,OpenCV Mat对象基本上是一个numpy数组。他们非常可以互换。 – zindarod

0

我面临类似的问题,当我试图将图像64F转换为CV_U8时,我会以黑屏结束。

link将帮助您了解数据类型和转换。以下是适合我的代码。

from skimage import img_as_ubyte 
cv_image = img_as_ubyte(any_skimage_image)