I was trying to posterize an image in python using opencv, after some time of searching i found a lead in openCV documentations. But as you can see its for rgb image and what I've got is a gray-scale image, i did it anyways and got weird outputs. i tweaked some places in the code and got even weirder outputs. Can someone please explain whats going on ?
EDIT:
My code
import numpy as np
import cv2
img = cv2.imread('Lenna.png')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
Z = np.float32(gray)
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 8
ret,label,center=cv2.kmeans(Z,K,None,criteria,10,cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
res = center[label.flatten()]
cv2.imshow('res',res)
cv2.waitKey(0)
cv2.destroyAllWindows()
Input image:
Output Image:
Can someone please explain whats going on ?
Kmeans input is a vector of vectors, or in a lot of cases, a vector of pixels or vector of 2D/3D points. In your code you are passing an image, which is a vector of the values in a row. That is why you get this weird values.
Simple, reshape the input to be a 1D vector of grey values.
Z = img.reshape((-1,1))
This way, it will try to use each grey value as input to cluster them (group them) and then it will label each value accordingly.