我正在创建一个图像处理程序,我想测量两个 numpy 直方图之间的 wasserstein 距离。这两个直方图是用函数numpy.histogram创建的我像这样从 scipy.stats 包中尝试了 wasserstein_distancefrom 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 verticesParams: 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 imagewidth = image.shape[1]height = image.shape[0]mask = Image.new('L', (width, height),value )# Draw your mask based on polygonImageDraw.Draw(mask).polygon(polygon, outline=1, fill=abs(value-1))# Covert to np arraymask = np.array(mask).astype(bool)return mask比创建直方图的函数def compute_histogram(mask, image):"""Returns histogram for image region defined by mask for each channelParams: 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
1 回答
慕慕森
TA贡献1856条经验 获得超17个赞
感谢 SpghttCd 解决方案很简单......我只需要更换
wasserstein_distance(histogram1, histogram2)
和
wasserstein_distance(histogram1[0], histogram2[0])
添加回答
举报
0/150
提交
取消