[英]Projecting a grayscale 2D numpy image into RGB?
I have a grayscale numpy image ( shape=(1024, 1024, 1)
, dtype=float
) that I'm trying to translate into the same image, but with the grayscale values assigned to the red channel (ie. the same image but in redscale).我有一个灰度 numpy 图像( shape=(1024, 1024, 1)
, dtype=float
),我试图将其转换为相同的图像,但将灰度值分配给红色通道(即相同的图像但红色刻度)。
Here's the original image:这是原始图像:
Which is generated using numpy:使用 numpy 生成:
def create_mandelbrot_matrix(width, height, max_iter=100):
X = np.linspace(-2, 1, width)
Y = np.linspace(-1, 1, height)
#broadcast X to a square array
C = X[:, None] + 1J * Y
#initial value is always zero
Z = np.zeros_like(C)
exit_times = max_iter * np.ones(C.shape, np.int32)
mask = exit_times > 0
for k in range(max_iter):
Z[mask] = Z[mask] * Z[mask] + C[mask]
mask, old_mask = abs(Z) < 2, mask
#use XOR to detect the area which has changed
exit_times[mask ^ old_mask] = k
return exit_times.T
def mandelbrot_image(width, height, max_iter=100):
mandelbrot_matrix = create_mandelbrot_matrix(width, height, max_iter)
img = np.expand_dims(mandelbrot_matrix, axis=2)
return img
This function results in a totally different image from the original:此 function 生成的图像与原始图像完全不同:
def mandelbrot_red_image(w, h):
mandelbrot_img = mandelbrot_image(w, h)
print(mandelbrot_img.shape) # (1024, 1024, 1)
img = np.zeros((w, h, 3))
img[:, :, 0] = mandelbrot_img_int.reshape((w, h))
return img
I dont know how your mandelbrot_image works, but image shapes are usually (h, w), due to the number of lines in a matrix being the first dimension, and the height.我不知道你的 mandelbrot_image 是如何工作的,但图像形状通常是(h,w),因为矩阵中的行数是第一维,而高度。
Another point is that, maybe your dtype is not 'uint8', I had to do a conversion in order to the image appear properly.另一点是,也许您的 dtype 不是“uint8”,我必须进行转换才能正确显示图像。
This code worked for me这段代码对我有用
from cv2 import cv2
import numpy as np
img = cv2.imread('./mandelbrot.png', cv2.IMREAD_GRAYSCALE)
h, w = img.shape
color_img = np.zeros([h, w, 3])
color_img[:, :, 2] = img # In opencv images are BGR
cv2.imshow('color_mandelbrot', color_img.astype('uint8'))
cv2.waitKey(0)
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.