python - Python中图像的交互式像素信息?

标签 python image image-processing matplotlib scikit-image

短版: 有没有一种 Python 方法来显示实时显示像素索引和强度的图像?因此,当我将光标移到图像上时,我有一个不断更新的显示,例如 pixel[103,214] = 198 (用于灰度)或 pixel[103,214] = (138,24,211) 为 rgb?

加长版:

假设我打开一个保存为 ndarray im 的灰度图像并使用 matplotlib 中的 imshow 显示它:

im = plt.imread('image.png')
plt.imshow(im,cm.gray)

我得到的是图像,在窗口框架的右下角,像素索引的交互式显示。除了它们不完全是,因为这些值不是整数:例如 x=134.64 y=129.169

如果我以正确的分辨率设置显示:

plt.axis('equal')

x 和 y 值仍然不是整数。

spectral 包中的 imshow 方法做得更好:

import spectral as spc
spc.imshow(im)

然后在右下角我现在有 pixel=[103,152] 例如。

但是,这些方法都不会显示像素值。所以我有两个问题:

  1. matplotlib 中的 imshow(以及 scikit-image 中的 imshow 是否可以强制显示正确的(整数)像素索引?
  2. 可以扩展这些方法中的任何一个以显示像素值吗?

最佳答案

有几种不同的方法可以解决这个问题。

您可以对 ax.format_coord 进行猴子补丁,类似于 this official example .我将在这里使用一种稍微“pythonic”的方法,它不依赖于全局变量。 (请注意,我假设没有指定 extent kwarg,类似于 matplotlib 示例。要完全通用,您需要执行 a touch more work 。)

import numpy as np
import matplotlib.pyplot as plt

class Formatter(object):
    def __init__(self, im):
        self.im = im
    def __call__(self, x, y):
        z = self.im.get_array()[int(y), int(x)]
        return 'x={:.01f}, y={:.01f}, z={:.01f}'.format(x, y, z)

data = np.random.random((10,10))

fig, ax = plt.subplots()
im = ax.imshow(data, interpolation='none')
ax.format_coord = Formatter(im)
plt.show()

enter image description here

或者,只是为了插入我自己的项目之一,您可以使用 mpldatacursor为了这。如果您指定 hover=True,则只要您将鼠标悬停在已启用的艺术家上,该框就会弹出。 (默认情况下,它仅在单击时弹出。)请注意,mpldatacursor 确实将 extentorigin kwargs 处理为 imshow 正确。

import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor

data = np.random.random((10,10))

fig, ax = plt.subplots()
ax.imshow(data, interpolation='none')

mpldatacursor.datacursor(hover=True, bbox=dict(alpha=1, fc='w'))
plt.show()

enter image description here

另外,我忘了提到如何显示像素索引。在第一个例子中,它只是假设 i, j = int(y), int(x)。如果您愿意,可以添加它们来代替 xy

使用 mpldatacursor,您可以使用自定义格式化程序指定它们。 ij 参数是正确的像素索引,与绘制图像的 extentorigin 无关。

例如(注意图像的 extent 与显示的 i,j 坐标):

import numpy as np
import matplotlib.pyplot as plt
import mpldatacursor

data = np.random.random((10,10))

fig, ax = plt.subplots()
ax.imshow(data, interpolation='none', extent=[0, 1.5*np.pi, 0, np.pi])

mpldatacursor.datacursor(hover=True, bbox=dict(alpha=1, fc='w'),
                         formatter='i, j = {i}, {j}\nz = {z:.02g}'.format)
plt.show()

enter image description here

关于python - Python中图像的交互式像素信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704490/

相关文章:

Python 序列(元组)

python - 如何对具有最高(接近+1)或最低(接近零)相关系数的两个变量的数据点进行采样?

python - 谷歌 API google.auth.exceptions.RefreshError : 'invalid_scope: Bad Request'

python - OpenCV Python equalizeHist 彩色图像

c++ - 使用 OpenCV 和 C++ 将图像帧拆分为 8*8 用于 DCT

python - Scrapy在什么情况下会抛出 "Connection was closed cleanly"错误?

html - 段落重叠图像

html - 如何在同一个div中将图像和文本居中

node.js - OpenCV - 将图像保存在 DB Nodejs 中

java - setRGB() 似乎没有改变颜色