Python 如何将numpy数组更改为灰度opencv图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24124458/
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
How to change numpy array into grayscale opencv image
提问by Leopoldo
How can I change numpy array into grayscale opencv image in python?
After some processing I got an array with following atributes: max value is: 0.99999999988,
min value is 8.269656407e-08 and type is: <type 'numpy.ndarray'>
. I can show it as an image using cv2.imshow()
function, but I can't pass it into cv2.AdaptiveTreshold()
function because it has wrong type:
如何在python中将numpy数组更改为灰度opencv图像?经过一些处理,我得到了一个具有以下属性的数组:最大值为:0.99999999988,最小值为 8.269656407e-08,类型为:<type 'numpy.ndarray'>
。我可以使用cv2.imshow()
函数将其显示为图像,但我无法将其传递给cv2.AdaptiveTreshold()
函数,因为它的类型错误:
error: (-215) src.type() == CV_8UC1 in function cv::adaptiveThreshold
How can I convert this np.array to correct format?
如何将此 np.array 转换为正确的格式?
采纳答案by Aurelius
As the assertion states, adaptiveThreshold()
requires a single-channeled 8-bit image.
正如断言所述,adaptiveThreshold()
需要单通道 8 位图像。
Assuming your floating-point image ranges from 0 to 1, which appears to be the case, you can convert the image by multiplying by 255 and casting to np.uint8
:
假设您的浮点图像范围从 0 到 1,这似乎是这种情况,您可以通过乘以 255 并强制转换为来转换图像np.uint8
:
float_img = np.random.random((4,4))
im = np.array(float_img * 255, dtype = np.uint8)
threshed = cv2.adaptiveThreshold(im, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY, 3, 0)
回答by BarzanHayati
I need to convert closed image(morphological closing) to binary, and after checking @Aurelius solution, This one work for me better than mentioned solution.
我需要将闭合图像(形态闭合)转换为二进制,并在检查@Aurelius 解决方案后,这比提到的解决方案更适合我。
mask_gray = cv2.normalize(src=mask_gray, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
回答by Praveen Manupati
This one worked for me:
这个对我有用:
uint_img = np.array(float_arr*255).astype('uint8')
grayImage = cv2.cvtColor(uint_img, cv2.COLOR_GRAY2BGR)