【问题标题】:How to calculate the mean pixel value inside an elipse area如何计算椭圆区域内的平均像素值
【发布时间】:2020-12-26 09:43:02
【问题描述】:

我想比较一个区域内像素强度的差异,对于这样的任务,我正在尝试使用 matplotlib 将椭圆绘制到 tiff 格式文件。我想做的是画两个椭圆来区分眼睛和巩膜,通过画两个椭圆来分开两者并获得两个区域的平均值,例如:

我想分别计算第一个椭圆区域和第二个区域内的平均值,以观察这两个区域之间的差异。

这是生成椭圆的示例,我想从两个区域内计算均值:

Image with elipses

用于坐标可视化的 Tiff 图像图:

用于生成省略号的代码:

import matplotlib.image
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
figure, ax = plt.subplots(1)
ax.imshow(img)
ax.add_patch(mpatches.Ellipse((30, 24),15,8, edgecolor='black', facecolor="none"))
ax.add_patch(mpatches.Ellipse((30, 24),30,16, edgecolor='black', facecolor="none"))
img_PIL.save(r'C:/Users/image/eye.tif')

【问题讨论】:

  • 你实际上并没有向 ax 添加任何东西...使用 ax.add_patch(mpl.patches.Ellipse(....))
  • 谢谢,它解决了绘图的问题,接下来要计算一下

标签: python numpy matplotlib image-processing python-imaging-library


【解决方案1】:

您可以定义一个椭圆的方程并将其用作掩码,以查看 tiff 数组元素是否在定义的椭圆内,如果是,则对它们进行平均,如下所示:

import numpy as np
import matplotlib.pyplot as plt
plt.ion()

#read/define the tiff array
img_array = np.random.rand(101,101)
plt.contourf(img_array)

#define ellipse parameters and equation (google equation for ellipse)
h = 51
k = 51
a = 10
b = 30

def _in_ellipse(x, y, h, k, a, b):
    z = ((x-h)**2)/a**2 + ((y-k)**2)/b**2
    if z < 1: #the equation is ^ this expression == 1
        return True
    else:
        return False

#vectorize for using on arrays
in_ellipse = np.vectorize(_in_ellipse)

#make a True mask within ellipse
mask = in_ellipse(*np.indices(img_array.shape), h,k,a,b)
plt.contourf(mask)

plt.contourf(np.where(mask, img_array, np.nan))

avg = np.nanmean(np.where(mask, img_array, np.nan))

如果您想调整蒙版在椭圆圆周上的行为方式,还可以在其中添加一个阈值关键字

def _in_ellipse(x, y, h, k, a, b, thresh=1):
    z = ((x-h)**2)/a**2 + ((y-k)**2)/b**2
    if z < thresh:
        return True
    else:
        return False

in_ellipse = np.vectorize(_in_ellipse)
mask = in_ellipse(*np.indices(img_array.shape), h,k,a,b,1.02)

当然还有更精细的方法,也许是 opencv 方法,但这是最简单的方法

【讨论】:

  • 很酷,但是您能解释一下如何将这些椭圆塑造成环形/椭圆形环吗?我以为面具会处理它,但不完全是
  • 我不确定你的意思,你能改写这个问题吗?你是在问如何改变椭圆的形状?
  • 有点。我试图做环状椭圆,没有填充物,并计算环边界内的面积。按照你的代码,任何人都会得到类似磁盘的省略号
  • 您必须为 scelra 和 iris 制作一个遮罩,然后制作第三个遮罩,这是两者的区别,这将为您提供“外”和“内”椭圆跨度>
  • 对不起的意思是-会给你“环”椭圆^
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多