Reputation: 488
Is there a way to convert an image into a vectorized form such as as follows:
I have looked this up searching for CNN, Pillow and CV2 methods however I didn't find any available resource online to implement this image transformation.
Appreciating your help on this matter.
Normal Image:
Vectorized Image:
Update:
I have implemented image segmentation using SLIC method, the following is new code and Resultant Image. As can be seen, the new image is close to the vectorized image(desired outcome) however the quality/detail difference is still alot.
Any further ideas?
from skimage import data, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt
from PIL import Image
from skimage import io
path='/home/user/Desktop/Image1.jpeg'
img = io.imread(path)
labels1 = segmentation.slic(img, compactness=50, n_segments=5000,
start_label=1)
out1 = color.label2rgb(labels1, img, kind='avg', bg_label=0)
out1 = Image.fromarray(out1, 'RGB')
out1.save('/home/user/Desktop/1.png')
g = graph.rag_mean_color(img, labels1, mode='similarity')
labels2 = graph.cut_normalized(labels1, g)
out2 = color.label2rgb(labels2, img, kind='avg', bg_label=0)
out2 = Image.fromarray(out2, 'RGB')
out2.save('/home/user/Desktop/2.png')
fig, ax = plt.subplots(nrows=2, sharex=True, sharey=True, figsize=(6, 8))
ax[0].imshow(out1)
ax[1].imshow(out2)
for a in ax:
a.axis('off')
plt.tight_layout()
plt.show()
New Image(N_Segments=2000)
New Image (N_segments=5000, took 5 minutes of computational time)
Upvotes: 7
Views: 13099
Reputation: 86
For those who want a simple and fast python solution:
from matplotlib.image import imread, imsave
from scipy import ndimage
from sklearn.cluster import KMeans
def segment_image(image, n_segments, smoothing_sigma):
smoothed = ndimage.gaussian_filter(image, (smoothing_sigma, smoothing_sigma, 0))
kmeans = KMeans(n_segments)
segment_ids = kmeans.fit_predict(smoothed.reshape(-1, 3)).reshape(*image.shape[:2])
new_image = kmeans.cluster_centers_.astype('uint8')[segment_ids]
return new_image
image = imread('yCMXP.jpg')
segmented = segment_image(image, 8, 3)
imsave('segmented.png', segmented)
The result:
The quality is a bit lower than the expected result but it gets the job done by a fast and extendable python script.
Upvotes: 0