[英]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.