繁体   English   中英

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

[英]Projecting a grayscale 2D numpy image into RGB?

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

这是原始图像:

原始灰度图像

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

此 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

问题红标图像

我不知道你的 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()

暂无
暂无

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

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