[2019-07-31] No machine learning clustering unsupervised learning of the K-Means algorithm instance (image segmentation)

sample:

Code:

Import numpy AS NP
 Import PIL.Image AS Image
 from sklearn.cluster Import KMeans 

DEF the loadData (filePath): 
    F = Open (filePath, ' RB ' ) # binary form open file 
    Data = [] 
    IMG = Image.open (F) 
    m , n- = img.size # acquired image size 
    for I in Range (m): # each pixel to the RGB color process 0-1 
        for J in Range (n-): 
            X, Y, Z = img.getpixel ( (i, J)) #0,0,0 black color is like other digital 
            # Print (the X-, the y-, z) 
            data.append ([the X-/ 256.0, the y-/ 256.0, z / 256.0]) # two-dimensional list [0.0, 0.0, 0.0] 
    f.close ()
     # Print (data) 
    return np.mat (data), m, n- # returns the data in a matrix form, and the image size 

imgData, Row, COL = the loadData ( ' D: / python_source / Machine_study / MOOC course data / program data / integer division /bull.jpg FIG clustering ' )
 # Print (imgData, Row, COL) 
label = KMeans (= n_clusters. 4 ) .fit_predict (imgData)
 # clustering obtained for each pixel belongs category 
label = label.reshape ([Row, COL]) # two-dimensional list 
# Print (label) 
pic_new = image.new (" L " , (Row, COL)) # after the creation of a new grayscale save the clustering effect 
for i in the Range (Row): # i, J is the image pixels, such as 640 * 480 according to the respective categories. Add picture gradation values 
    for J in Range (COL): 
        pic_new.putpixel ((I, J), int ( 256 / (label [I] [J] + 1'd ))) 
pic_new.save ( " Result-bull- 4.jpg " , " JPEG " )

 

Renderings:

Guess you like

Origin www.cnblogs.com/ymzm204/p/11279016.html