Reputation: 135
I want to segment an image using slic superpixels and then replace the original colour of a superpixel with the average colour of said 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)
I get the errorValueError: Label and intensity image must have thesame shape.
Segments shape is (512,512) and img shape in (512,512,3). What is the correct use of regionprops
in my case?
Upvotes: 4
Views: 2011
Reputation: 60695
According to the documentation, regionprops
can only quantify a grey-value image, and won't work for color.
A simple solution would be to measure average intensity in each channel separately, and combine the results:
out = np.empty_like(img)
for ii in range(3):
regions = regionprops(segments, intensity_image=img[:,:,ii])
# paint, and write to out[:,:,ii]
Using DIPlib this can be done quite simply (disclaimer: I'm an author):
import diplib as dip
segments = segments.astype('uint32') # 64-bit types not accepted by DIPlib
msr = dip.MeasurementTool.Measure(segments, img, ['Mean'])
out = dip.ObjectToMeasurement(segments, msr['Mean'])
out.Show()
Upvotes: 1
Reputation: 135
I followed the first recommendation of the accepted answer. Working version of my code :
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()
Upvotes: 4