In [1]:
Copied!
import numpy as np
from PIL import Image
from fcmeans import FCM
import numpy as np
from PIL import Image
from fcmeans import FCM
Getting and rescaling the image¶
In [2]:
Copied!
image = Image.open('images/oarsman.jpeg') # read image (oarsman at https://omadson.github.io/photos/)
N, M = image.size # get the number of columns (N) and rows (M)
image # show resized image
image = Image.open('images/oarsman.jpeg') # read image (oarsman at https://omadson.github.io/photos/)
N, M = image.size # get the number of columns (N) and rows (M)
image # show resized image
Out[2]:
Transforming image into a data set¶
In [3]:
Copied!
X = (
np.asarray(image) # convert a PIL image to np array
.reshape((N*M, 3)) # reshape the image to convert each pixel to an instance of a data set
)
X = (
np.asarray(image) # convert a PIL image to np array
.reshape((N*M, 3)) # reshape the image to convert each pixel to an instance of a data set
)
Creating and fitting the model¶
In [4]:
Copied!
fcm = FCM(n_clusters=10) # create a FCM instance with 10 clusters
fcm.fit(X) # fit the model
fcm = FCM(n_clusters=10) # create a FCM instance with 10 clusters
fcm.fit(X) # fit the model
Pixel quantization¶
In [5]:
Copied!
labeld_X = fcm.predict(X) # get the label of each data point
transformed_X = fcm.centers[labeld_X] # pixel quantization into the centers
labeld_X = fcm.predict(X) # get the label of each data point
transformed_X = fcm.centers[labeld_X] # pixel quantization into the centers
Converting and saving image¶
In [6]:
Copied!
quatized_array = (
transformed_X
.astype('uint8') # convert data points into 8-bit unsigned integers
.reshape((M, N, 3)) # reshape image
)
quatized_image = Image.fromarray(np.asarray(quatized_array)) # convert array into a PIL image object
quatized_image.save('images/oarsman_10colors.jpg') # save image
quatized_array = (
transformed_X
.astype('uint8') # convert data points into 8-bit unsigned integers
.reshape((M, N, 3)) # reshape image
)
quatized_image = Image.fromarray(np.asarray(quatized_array)) # convert array into a PIL image object
quatized_image.save('images/oarsman_10colors.jpg') # save image
In [7]:
Copied!
side_by_side = Image.fromarray(
np.hstack([
np.array(image),
np.array(quatized_image)
])
)
side_by_side
side_by_side = Image.fromarray(
np.hstack([
np.array(image),
np.array(quatized_image)
])
)
side_by_side
Out[7]: