Our Blog

Latest News

Image Processing KMeans

This code performs several image processing tasks using the OpenCV library. It first loads an image file using the imread function from OpenCV. Then it pre-processes the image by converting it to grayscale and applying a Gaussian blur to filter out noise.

Next, the code uses the Canny function from OpenCV to detect edges in the image. It then uses the KMeans function from the sklearn library to cluster the image into two groups based on the edges detected.

The code then uses the Hough transform to detect lines and circles in the image. The HoughLinesP function is used to detect lines, and the HoughCircles function is used to detect circles. If lines or circles are detected, the code draws them on the original image using the line and circle functions from OpenCV.

Finally, the code displays the modified image using the cv2_imshow function from the google.colab.patches library, which is a utility function for displaying images in a Jupyter notebook. The code also saves the modified image to a file using the imwrite function from OpenCV.

from google.colab.patches import cv2_imshow
import numpy as np # for data analysis
from sklearn.cluster import KMeans # for machine learning

# Load the image
image = cv2.imread('mars0001.jpg')

# Pre-process the image
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# Apply a Gaussian blur to filter out noise
blurred = cv2.GaussianBlur(gray, (5, 5), 0)

# Use Canny edge detection to find edges in the image
edges = cv2.Canny(blurred, 100, 200)

# Use KMeans to cluster the image
kmeans = KMeans(n_clusters=2).fit(edges.reshape(-1, 1))
clusters = kmeans.predict(edges.reshape(-1, 1))

# Use NumPy to count the number of pixels in each cluster
counts = np.bincount(clusters)

# Use Hough lines to detect lines in the image
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 50, minLineLength=50, maxLineGap=10)

# Loop through the lines and draw them on the image
for line in lines:
    x1, y1, x2, y2 = line[0]
    cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

if lines is not None:
    for line in lines:
        x1, y1, x2, y2 = line[0]
        cv2.line(image, (x1, y1), (x2, y2), (0, 0, 255), 2)

# Use Hough circles to detect circles in the image
circles = cv2.HoughCircles(gray, cv2.HOUGH_GRADIENT, 1, 20, param1=50, param2=30, minRadius=0, maxRadius=0)

# Loop through the circles and draw them on the image
if circles is not None:
    circles = np.round(circles[0, :]).astype("int")
    for (x, y, r) in circles:
        cv2.circle(image, (x, y), r, (0, 255, 0), 4)
        cv2.rectangle(image, (x - 5, y - 5), (x + 5, y + 5), (0, 128, 255), -1)

# Show the image

cv2.imwrite('output.jpg', image, [cv2.IMWRITE_JPEG_QUALITY, 95])
Statement Sentiment Logistic Regression