在 Python 中从图像中提取每个像素的 x,y 坐标 [英] Extract x,y coordinates of each pixel from an image in Python

查看:256
本文介绍了在 Python 中从图像中提取每个像素的 x,y 坐标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一张彩色图像,我已将其加载到一个 numpy 尺寸数组 (200 x 300 x 3) 中.图像中总共有 60,000 个像素.我试图从代表像素 1 的 左上角 开始提取每个像素的宽度、高度 (x,y) 坐标:

Let's say I have a color image that I've loaded into a numpy array of dimensions (200 x 300 x 3). In total, there are 60,000 pixels in the image. I'm trying to extract the width,height (x,y) coordinates of each pixel starting from the upper left top corner representing pixel 1 such that:

pixel#   x    y
1        0    0
2        1    0
.
.
301      0    1
302      1    1
.
.
60,000   299 199   

我很想使用 for 循环以更手动的方式执行此操作,但是否有库或更有效的方法来获取每个像素的坐标值?

I'm tempted to use a for loop to do this in a more manual-nature but are there libraries or more effective ways to get those coordinate values for each pixel as such?

推荐答案

由于您显示的格式似乎是 Pandas,我将使用 Pandas 显示输出,但您可以仅使用打印.:)

Since the format you're showing seems to be pandas, I'll present the output with pandas, but you could just use a mere print. :)

我什至在评论中包含了一个 n-dimension 解决您的问题.

I even included a n-dimension solution to your problem as comments.

import numpy as np
from itertools import product

arr = np.array([
    list(range(300))
    for _ in range(200)
])

print(arr.shape)
# (200, 300)

pixels = arr.reshape(-1)

""" n-dimension solution
    coords = map(range, arr.shape)
    indices = np.array(list( product(*coords) ))
"""
xs = range(arr.shape[0])
ys = range(arr.shape[1])
indices = np.array(list(product(xs, ys)))

import pandas as pd
pd.options.display.max_rows = 20

index = pd.Series(pixels, name="pixels")
df = pd.DataFrame({
    "x" : indices[:, 0],
    "y" : indices[:, 1]
}, index=index)
print(df)
#           x    y
# pixels          
# 0         0    0
# 1         0    1
# 2         0    2
# 3         0    3
# 4         0    4
# 5         0    5
# 6         0    6
# 7         0    7
# 8         0    8
# 9         0    9
# ...     ...  ...
# 290     199  290
# 291     199  291
# 292     199  292
# 293     199  293
# 294     199  294
# 295     199  295
# 296     199  296
# 297     199  297
# 298     199  298
# 299     199  299

# [60000 rows x 2 columns]

这篇关于在 Python 中从图像中提取每个像素的 x,y 坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆