将灰度 2D numpy 图像投影到 RGB?

Projecting a grayscale 2D numpy image into RGB?

我有一个灰度 numpy 图像(shape=(1024, 1024, 1)dtype=float),我试图将其转换为同一图像,但灰度值分配给了红色通道(即相同的图像,但在 redscale 中)。

这是原始图片:

使用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

此函数生成与原始图像完全不同的图像:

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

我不知道你的 mandelbrot_image 是如何工作的,但是图像的形状通常是 (h, w),因为矩阵中的行数是第一维,而高度是。

还有一点,可能你的dtype不是'uint8',我必须做一个转换才能正确显示图像。

这段代码对我有用

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()