我想使用切片超像素对图像进行分割,然后用所述超像素的平均颜色替换超像素的原始颜色。
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
的正确用法是什么?
答案 0 :(得分:1)
根据documentation,regionprops
只能量化灰度图像,而不能用于彩色图像。
一个简单的解决方案是分别测量每个通道中的平均强度,并将结果组合起来:
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()
答案 1 :(得分:0)
我遵循了已接受答案的第一个建议。我的代码的工作版本:
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()