├── ImgSegment.py └── README.md /ImgSegment.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Created on Wed Jul 24 10:39:21 2019 5 | 6 | @author: nageshsinghchauhan 7 | """ 8 | #SImple image segmentation using K-Means clustering algo 9 | 10 | #color clustering 11 | #Image segmentation from video using OpenCV and K-means clustering 12 | import numpy as np 13 | import cv2 14 | import matplotlib.pyplot as plt 15 | original_image = cv2.imread("/Users/nageshsinghchauhan/Desktop/images/p.jpg") 16 | # Converting from BGR Colours Space to HSV 17 | img=cv2.cvtColor(original_image,cv2.COLOR_BGR2RGB) 18 | vectorized = img.reshape((-1,3)) 19 | # convert to np.float32 20 | vectorized = np.float32(vectorized) 21 | # Here we are applying k-means clustering so that the pixels around a colour are consistent and gave same BGR/HSV values 22 | # define criteria, number of clusters(K) and apply kmeans() 23 | criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) 24 | # We are going to cluster with k = 2, because the image will have just two colours ,a white background and the colour of the patch 25 | K = 4 26 | attempts=10 27 | ret,label,center=cv2.kmeans(vectorized,K,None,criteria,attempts,cv2.KMEANS_PP_CENTERS) 28 | # Now convert back into uint8 29 | #now we have to access the labels to regenerate the clustered image 30 | center = np.uint8(center) 31 | res = center[label.flatten()] 32 | res2 = res.reshape((img.shape)) 33 | #res2 is the result of the frame which has undergone k-means clustering 34 | figure_size = 15 35 | plt.figure(figsize=(figure_size,figure_size)) 36 | plt.subplot(1,2,1),plt.imshow(img) 37 | plt.title('Original'), plt.xticks([]), plt.yticks([]) 38 | plt.subplot(1,2,2),plt.imshow(res2) 39 | plt.title('K = %i' % K), plt.xticks([]), plt.yticks([]) 40 | plt.show() 41 | 42 | #canny edge detection 43 | edges = cv2.Canny(img,100,200) 44 | plt.figure(figsize=(figure_size,figure_size)) 45 | plt.subplot(1,2,1),plt.imshow(img) 46 | plt.title('Original Image'), plt.xticks([]), plt.yticks([]) 47 | plt.subplot(1,2,2),plt.imshow(edges,cmap = 'gray') 48 | plt.title('Edge Image'), plt.xticks([]), plt.yticks([]) 49 | 50 | plt.show() 51 | 52 | """ 53 | #video 54 | import cv2 55 | import numpy as np 56 | 57 | # Create a VideoCapture object and read from input file 58 | cap = cv2.VideoCapture("/Users/nageshsinghchauhan/Documents/bb.mkv") 59 | 60 | # Check if camera opened successfully 61 | if (cap.isOpened()== False): 62 | print("Error opening video file") 63 | 64 | # Read until video is completed 65 | while(cap.isOpened()): 66 | # Capture frame-by-frame 67 | ret, frame = cap.read() 68 | if ret == True: 69 | # Display the resulting frame 70 | cv2.imshow('Frame', frame) 71 | # Press Q on keyboard to exit 72 | if cv2.waitKey(25) & 0xFF == ord('q'): 73 | break 74 | # Break the loop 75 | else: 76 | break 77 | # When everything done, release 78 | # the video capture object 79 | cap.release() 80 | # Closes all the frames 81 | cv2.destroyAllWindows() 82 | """ 83 | 84 | 85 | 86 | 87 | #plotting an Image in 3D color space. 88 | import matplotlib.pyplot as plt 89 | from mpl_toolkits.mplot3d import Axes3D 90 | import cv2 91 | 92 | #read image 93 | img = cv2.imread("/Users/nageshsinghchauhan/Documents/bb.mkv") 94 | 95 | #convert from BGR to RGB 96 | img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) 97 | 98 | #get rgb values from image to 1D array 99 | r, g, b = cv2.split(img) 100 | r = r.flatten() 101 | g = g.flatten() 102 | b = b.flatten() 103 | 104 | #plotting 105 | fig = plt.figure() 106 | ax = Axes3D(fig) 107 | ax.scatter(r, g, b) 108 | plt.show() 109 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Image-segmentation-K-means-clustering 2 | 3 | Image segmentation is an important step in image processing, and it seems everywhere if we want to analyze what’s inside the image. For example, if we seek to find if there is a chair or person inside an indoor image, we may need image segmentation to separate objects and analyze each object individually to check what it is. Image segmentation usually serves as the pre-processing before pattern recognition, feature extraction, and compression of the image. 4 | 5 | 6 | Image segmentation is the process of partitioning a digital image into multiple distinct regions containing each pixel(sets of pixels, also known as superpixels) with similar attributes. 7 | 8 | For more information, checkout this article. 9 | 10 | 11 | https://www.theaidream.com/post/introduction-to-image-segmentation-with-k-means-clustering 12 | --------------------------------------------------------------------------------