使用NumPy与Matplotlib绘制RGB矩阵时颜色显示异常的问题排查
Hey there! Let's walk through the issues with your code and get that flag looking right.
Key Problems in Your Current Code
Mismatched color value range and data type:
Matplotlib'simshow()treats floating-point arrays as having values in the range0.0to1.0. Your code creates a float array (the default fornp.empty()) but assigns RGB values from0to255—all these values get clamped to1.0, which is why your colors are messed up. For 0-255 RGB values, you need an integer array of typeuint8(8-bit unsigned integer).Tiny image dimensions:
Your array is(1, 3, 3)—that's a single pixel tall and 3 pixels wide. Even if the colors were correct, you'd barely be able to see anything! Belgian flags are vertical stripes, so you want a taller, wider canvas to display them properly.
Fixed Code Example
Here's adjusted code that addresses both issues and renders the Belgian flag correctly:
import numpy as np import matplotlib.pyplot as plt # Create a properly sized RGB array with uint8 type (for 0-255 RGB values) flag_height = 200 flag_width = 600 flag = np.zeros((flag_height, flag_width, 3), dtype=np.uint8) # Split the width into 3 equal vertical blocks for each color block_width = flag_width // 3 # Assign colors to each stripe (black, yellow, red) flag[:, :block_width, :] = (0, 0, 0) flag[:, block_width:2*block_width, :] = (254, 240, 71) flag[:, 2*block_width:, :] = (255, 55, 14) # Display the flag without axes for a cleaner look plt.imshow(flag) plt.axis('off') plt.show()
What Changed?
- Data type set to
uint8:
Usingdtype=np.uint8tells NumPy and Matplotlib that we're working with standard 0-255 RGB values, so no clamping occurs. - Resized the flag:
A 200x600 canvas makes the vertical stripes clearly visible. - Proper stripe layout:
We split the width into three equal sections to match the Belgian flag's vertical stripe pattern.
Bonus: Using Floating-Point Arrays (If You Prefer)
If you want to stick with floating-point values, just divide your RGB values by 255 to fit the 0.0-1.0 range:
flag = np.zeros((200, 600, 3), dtype=np.float32) flag[:, :block_width, :] = (0/255, 0/255, 0/255) flag[:, block_width:2*block_width, :] = (254/255, 240/255, 71/255) flag[:, 2*block_width:, :] = (255/255, 55/255, 14/255)
内容的提问来源于stack exchange,提问作者blah_crusader

