You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用NumPy与Matplotlib绘制RGB矩阵时颜色显示异常的问题排查

Why Your Belgian Flag Isn't Displaying Correctly (And How to Fix It)

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's imshow() treats floating-point arrays as having values in the range 0.0 to 1.0. Your code creates a float array (the default for np.empty()) but assigns RGB values from 0 to 255—all these values get clamped to 1.0, which is why your colors are messed up. For 0-255 RGB values, you need an integer array of type uint8 (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?

  1. Data type set to uint8:
    Using dtype=np.uint8 tells NumPy and Matplotlib that we're working with standard 0-255 RGB values, so no clamping occurs.
  2. Resized the flag:
    A 200x600 canvas makes the vertical stripes clearly visible.
  3. 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:23