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

如何将像素坐标(x,y)转换为矩阵索引?技术实现咨询

从像素坐标(x,y)到二维矩阵索引的转换

Got it, let's break this down clearly for you—this conversion is straightforward once you align the coordinate systems properly.

1. First, align the coordinate rules

In almost all pixel/image systems, the pixel coordinates follow:

  • x: Horizontal axis, starts at the top-left corner, increases from left to right (e.g., leftmost pixel is x=0, next is x=1, etc.)
  • y: Vertical axis, also starts at the top-left corner, increases from top to bottom (topmost pixel is y=0, next row down is y=1, etc.)

Your C 2D matrix char *map[20][17] uses standard array indexing rules:

  • map[row][col]: row is the row index (starts at 0, counting from top to bottom of the matrix), col is the column index (starts at 0, counting from left to right).

2. The direct conversion formula

With the systems aligned, the mapping is simple:

  • Matrix row index = Pixel y coordinate
  • Matrix column index = Pixel x coordinate

So for a pixel at (x, y), the corresponding matrix element is:

map[y][x]

3. Let's test with your example matrix

Take the first row of your matrix:

"WWWWWWWWWWWWWWWW"  // This is row 0, corresponding to y=0
  • Pixel (0, 0) → map[0][0] → The first 'W' in the first row
  • Pixel (5, 0) → map[0][5] → The 6th 'W' in the first row

For the second row:

"WFFFFFFFFFFFFFFW"  // This is row 1, corresponding to y=1
  • Pixel (1, 1) → map[1][1] → The first 'F' in the second row

4. Don't forget boundary checks

Your matrix is 20 rows × 17 columns, so you must ensure the pixel coordinates stay within valid ranges to avoid memory access errors:

  • x must be between 0 and 16 (inclusive)
  • y must be between 0 and 19 (inclusive)

Here's a quick code snippet to handle this safely:

if (x >= 0 && x < 17 && y >= 0 && y < 20) {
    // Safely access the matrix element
    char target_pixel = map[y][x];
    // Do your modification here
} else {
    // Handle out-of-bounds coordinates
    printf("Error: Pixel coordinates are outside the matrix bounds!\n");
}

内容的提问来源于stack exchange,提问作者user7075574

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 06:48:18