切片超像素的平均颜色

Average colour of slic superpixel

我想使用切片超像素分割图像,然后用所述超像素的平均颜色替换超像素的原始颜色。

import numpy as np
import matplotlib.pyplot as plt
from skimage import io
from skimage.segmentation import slic, mark_boundaries
from skimage.data import astronaut
from skimage.measure import regionprops

img = astronaut()
segments = slic(img, n_segments=512, compactness=10,
            multichannel=True,
            enforce_connectivity=True,
            convert2lab=True)
regions = regionprops(segments, intensity_image=img)

我收到错误ValueError: Label and intensity image must have thesame shape. 段形状为 (512,512),img 形状为 (512,512,3)。在我的案例中 regionprops 的正确用法是什么?

根据documentationregionprops只能对灰度图像进行量化,对彩色图像不起作用。

一个简单的解决方案是分别测量每个通道的平均强度,然后合并结果:

out = np.empty_like(img)
for ii in range(3):
   regions = regionprops(segments, intensity_image=img[:,:,ii])
   # paint, and write to out[:,:,ii]

使用 PyDIP 这可以非常简单地完成(免责声明:我是作者):

import PyDIP as dip

segments = segments.astype('uint32')  # 64-bit types not accepted by PyDIP
msr = dip.MeasurementTool.Measure(segments, img, ['Mean'])
out = dip.ObjectToMeasurement(segments, msr['Mean'])
out.Show()

我遵循了已接受答案的第一个建议。我的代码的工作版本:

import matplotlib.pyplot as plt
from skimage.segmentation import slic
from skimage.data import astronaut
from skimage.measure import regionprops

def paint_region_with_avg_intensity(rp, mi, channel):
    for i in range(rp.shape[0]):
        img[rp[i][0]][rp[i][1]][channel] = mi

img = astronaut()
segments = slic(img, n_segments=512, compactness=10,
            multichannel=True,
            enforce_connectivity=True,
            convert2lab=True)

for i in range(3):
    regions = regionprops(segments, intensity_image=img[:,:,i])
    for r in regions:
        paint_region_with_avg_intensity(r.coords, int(r.mean_intensity), i)

plt.imshow(img)
plt.show()