我正在创建一个图像处理程序,我想测量两个 numpy 直方图之间的 wasserstein 距离。这两个直方图是用函数numpy.histogram创建的
我像这样从 scipy.stats 包中尝试了 wasserstein_distance
from scipy.stats import wasserstein_distance
wasserstein_distance(histogram1,histogram2)
但它给了我那个错误
ValueError:使用序列设置数组元素。
完整代码:
首先是计算距离的函数:
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
慕慕森
相关分类