我正在創(chuàng)建一個圖像處理程序,我想測量兩個 numpy 直方圖之間的 wasserstein 距離。這兩個直方圖是用函數(shù)numpy.histogram創(chuàng)建的我像這樣從 scipy.stats 包中嘗試了 wasserstein_distancefrom scipy.stats import wasserstein_distance wasserstein_distance(histogram1,histogram2)但它給了我那個錯誤ValueError:使用序列設置數(shù)組元素。完整代碼:首先是計算距離的函數(shù): def f_dist( histogram1 ,histogram2): return wasserstein_distance(histogram1,histogram2)比計算直方圖創(chuàng)建掩碼的函數(shù):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比創(chuàng)建直方圖的函數(shù)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條經(jīng)驗 獲得超17個贊
感謝 SpghttCd 解決方案很簡單......我只需要更換
wasserstein_distance(histogram1, histogram2)
和
wasserstein_distance(histogram1[0], histogram2[0])
添加回答
舉報
0/150
提交
取消