我正在创建一个图像处理程序,我想测量两个numpy直方图之间的wasserstein距离。 这两个直方图是使用函数numpy.histogram
创建的我像这样从scipy.stats包中尝试了wasserstein_distance
"require": {
"dr-que/x-y": "dev-master"
}
但这给了我这个错误
ValueError:设置具有序列的数组元素。
完整代码:
首先计算距离的函数:
from scipy.stats import wasserstein_distance
wasserstein_distance(histogram1,histogram2)
比计算用于创建直方图的蒙版的功能
def f_dist( histogram1 ,histogram2):
return wasserstein_distance(histogram1,histogram2)
比创建直方图的功能
def prepare_mask(polygon, image,value):
"""Returns binary mask based on input polygon presented as list of coordinates of vertices
Params:
polygon (list) - coordinates of polygon's vertices. Ex: [(x1,y1),(x2,y2),...] or [x1,y1,x2,y2,...]
image (numpy array) - original image. Will be used to create mask of the same size. Shape (H, W, C).
Output:
mask (numpy array) - boolean mask. Shape (H, W).
"""
# create an "empty" pre-mask with the same size as original image
width = image.shape[1]
height = image.shape[0]
mask = Image.new('L', (width, height),value )
# Draw your mask based on polygon
ImageDraw.Draw(mask).polygon(polygon, outline=1, fill=abs(value-1))
# Covert to np array
mask = np.array(mask).astype(bool)
return mask
现在是主要功能:
def compute_histogram(mask, image):
"""Returns histogram for image region defined by mask for each channel
Params:
image (numpy array) - original image. Shape (H, W, C).
mask (numpy array) - boolean mask. Shape (H, W).
Output:
list of tuples, each tuple (each channel) contains 2 arrays: first - computed histogram, the second - bins.
"""
# Apply binary mask to your array, you will get array with shape (N, C)
region = image[mask]
hist = np.histogram(region.ravel(), bins=256, range=[0, 255])
return hist
答案 0 :(得分:1)
感谢SpghttCd解决方案很简单...我只需要更换
wasserstein_distance(histogram1, histogram2)
使用
wasserstein_distance(histogram1[0], histogram2[0])