Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

k-means clustering and disabling clusters

img = path
img = cv2.imread(img)
img = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)
pixVal = img.reshape((-1,3))
pixVal = np.float(pixVal)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 100, 0.2)
# number of clusters (K)
k = 3
_, labels, (centers) = cv2.kmeans(pixVal, k, None,
                                  criteria, 10, cv2.KMEANS_RANDOM_CENTERS)
# convert back to 8 bit values
centers = np.uint8(centers)

# flatten the labels array
labels = labels.flatten()

# convert all pixels to the color of the centroids
segmented_image = centers[labels.flatten()]
# reshape back to the original image dimension
segmented_image = segmented_image.reshape(image.shape)
# show the image
plt.imshow(segmented_image)
plt.show()

# disable only the cluster number 2 (turn the pixel into black)
masked_image = np.copy(image)
# convert to the shape of a vector of pixel values
masked_image = masked_image.reshape((-1, 3))
# color (i.e cluster) to disable
cluster = 2
masked_image[labels == cluster] = [0, 0, 0]
# convert back to original shape
masked_image = masked_image.reshape(image.shape)
# show the image
plt.imshow(masked_image)
plt.show()
Comment

PREVIOUS NEXT
Code Example
Python :: mechanize python #5 
Python :: mechanize python #11 
Python :: mechanize python XE #28 
Python :: python how to close the turtle tab on click 
Python :: ~coinbase api 
Python :: django-filter field name greater than 
Python :: the webpage at http://127.0.0.1:8000/ might be temporarily down or it may have moved permanently to a new web address. django 
Python :: order dataframe by specific column c1 
Python :: django database specify schema 
Python :: generate jwt token just passing userid in rest_framework_simplejwt 
Python :: !value in python 
Python :: Add error message in django loginrequiredmixin 
Python :: raise httperror(req.full_url, code, msg, hdrs, fp) urllib.error.httperror: http error 429: too many requests 
Python :: Python find permutations of operators between each digit in a given string of digits will result in a particular answer 
Python :: Linear Search Python with enumerate 
Python :: splitting Feature and target using iloc 
Python :: to create an array with values that are spaced linearly in a specified interval 
Python :: how to sort list in python without sort function 
Python :: Convert Int to String Using F-strings 
Python :: how to change multiple index in list in python 
Python :: python occ display point 
Python :: pandas version for python 3.9 
Python :: uncompress zip file in pythonanywhere 
Python :: move python file 
Python :: Python NumPy rollaxis Function Syntax 
Python :: find duplicate row in python sqlite database 
Python :: Python NumPy vstack Function Example with 1d array 
Python :: Python NumPy hsplit Function 
Python :: Python how to use __le__ 
Python :: beaglebone install python 3.7 
ADD CONTENT
Topic
Content
Source link
Name
8+8 =