numpy 如何用数值表示双色matplotlib图形中的特定颜色?

14ifxucb  于 2022-12-18  发布在  其他
关注(0)|答案(2)|浏览(141)

作为我的项目的一部分,我生成了一个matplotlib图,这个图是一个双色图,由一个形状的numpy数组(1,128,128,1)绘制而成,如下所示

图中的黄色区域是我所需的区域,而整个区域用紫色表示。
有没有办法用数字表示图中的黄色区域?有没有可能得到
1.黄色区域与紫色区域的比值
1.与紫色区域相比,图形中黄色像素的数量
请帮帮我。

sy5wg1nm

sy5wg1nm1#

你没有提供代码,所以我只给予一个例子。把它应用到你的数组中。
这里你需要做的就是使用你绘制和使用的原始数组

c = np.count_nonzero(arr == yellow_value)

这将计算数组中所有值为黄色的元素。
然后你可以计算比率:

ratio = c/(128*128)

128*128代表数组中的像素总数。您可以通过数组维度将其参数化。

xxls0lw8

xxls0lw82#

有两种方法可以解决这个问题:
1-如果您有数组本身,则可以只设置值的阈值,计算低值和高值的计数,最后计算比率。
顺便说一下,在默认情况下,当你用“matplotlib”库绘制二维图形时,黄色代表高值,紫色代表低值。

代码:

import numpy as np
... 
array = make_arbitrary_array()

# Here, we are selecting the midrange as the threshold value,
#  you can change this as you see fit
threshold = (array.min() + array.max()) / 2

total_value_count = np.prod(array.shape)
high_value_count  = np.sum(array > threshold) 
low_value_count   = total_value_count - high_value_count

high_low_ratio = (high_value_count / low_value_count)
high_all_ratio = (high_value_count / total_value_count)
low_all_ratio  = (low_value_count  / total_value_count)

print(f"Ratio of yellow region over purple region {high_low_ratio*100:.3f}%")
print(f"Ratio of yellow region over total {high_all_ratio*100:.3f}%")
print(f"Ratio of purple region over total {low_all_ratio*100:.3f}%")

输出:

Ratio of yellow region over purple region 22.805%
Ratio of yellow region over total 18.570%
Ratio of purple region over total 81.430%

绘制的图像:Image of the Plot

2-如果没有访问numpy数组的权限,而只有访问plot的图像的权限;你需要把图像加载到Python中,把像素转换成一个数组,然后使用和(1)中相同的代码从数组中计算比率。
此方法可能存在一些问题,例如,图的插值效果可能不佳(例如在您的情况下,如果数组中只有两个值,则有绿色的像素,既不是黄色也不是紫色)。此外,您所拥有的图像应该已经保存为文件,这反过来意味着它可能是以有损的方式压缩的(如.JPEG文件)。如果您为您的情况使用无损压缩,如.PNG文件,效果会更好。
我正在使用OpenCV加载映像,您可以使用pip将其安装到您的环境中。要安装OpenCV,请在shell中运行以下行:pip install opencv-python

与代码位于同一文件夹中的图像:plot_image.png
代码:

import numpy as np
import cv2

# reading the values in grayscale to make it easier to process
img = cv2.imread("plot_image.png", cv2.IMREAD_GRAYSCALE)
array = np.array(img.data)

... # codes in the part (1)

输出:

Ratio of yellow region over purple region 22.805%
Ratio of yellow region over total 18.570%
Ratio of purple region over total 81.430%

使用这种方法,我们也可以获得与以前相同的输出。

相关问题