简体   繁体   English

如何从python中的现有二维数组数据创建灰度图像

[英]how to create an gray-scale image from existing 2D array data in python

I have a problem creating a grey-scale image from existing 2D array in python.我在从 python 中的现有二维数组创建灰度图像时遇到问题。

Supposing I have a 2D array, X at dimension 504x896 data type is unit8.假设我有一个二维数组,维度为 504x896 的 X 数据类型为 unit8。 How could I create a gray-scale image from this 2D array?我怎样才能从这个二维数组创建一个灰度图像? Will OpenCV provide an function for it or do I have to include other image processing library? OpenCV 会为其提供功能还是必须包含其他图像处理库?


I have tried this but it did not work for some reason.我试过这个,但由于某种原因它不起作用。 Given a 2D array z给定一个二维数组 z

dim = z.shape
h =  dim[0]
w = dim[1]

copy_image = np.zeros((h,w,1), np.uint8)
copy_image = z.copy();
cv2.imwrite("cpImage.bmp",copy_image)

This should work as expected.这应该按预期工作。 I have used Float32 as both arguments cv.CvtColor must have the same depth.我使用 Float32 作为两个参数 cv.CvtColor 必须具有相同的深度。

import numpy as np
import cv2
nArray = np.zeros((504, 896), np.float32) #Create the arbitrary input img
h,w = nArray.shape
cArray1 = cv2.CreateMat(h, w, cv2.CV_32FC3)
cArray2 = cv2.fromarray(nArray)
cv2.CvtColor(cArray2, cArray1, cv2.CV_GRAY2BGR)
cv2.imwrite("cpImage.bmp", cArray1)

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

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