Jay_Paranjape
Jay_Paranjape

Reputation: 3

Finding different boundaries around a set of points in an image

I have an image which looks something like this: here is the image

I need to make borders around the points such that they are divided into clusters. For example, the center of the image is one region. One other region can be the top of the image. How can I achieve this, with python preferably?

Upvotes: 0

Views: 793

Answers (1)

fmw42
fmw42

Reputation: 53247

Here is one way to do that in Python/OpenCV.

 - Read the input as unchanged, since it has transparency
 - Separate the base image and the alpha channel
 - Mask the base image with the alpha channel so as to make the white outer region with the text into all black
 - Convert that image into grayscale and then into black/white
 - Apply morphology close to connect all the dots in the regions
 - Find all contours larger than some minimum area
 - Draw the contours on the base image
 - Save the results


Input:

enter image description here

import cv2
import numpy as np

# read image with transparency
image = cv2.imread("dots.png", cv2.IMREAD_UNCHANGED)

# separate base image and alpha channel and make background under transparency into black to remove white border and text
base = image[:,:,0:3]
alpha = image[:,:,3]
alpha = cv2.merge([alpha,alpha,alpha])
img = cv2.bitwise_and(base, alpha)

# convert img to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

#do threshold on gray image
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY)[1]

# apply morphology close
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (15, 15))
close = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)

# Get contours
cnts = cv2.findContours(close, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
result = base.copy()
for c in cnts:
    area = cv2.contourArea(c)
    if area > 100:
        cv2.drawContours(result, [c], -1, (0, 255, 0), 1)

# display it
cv2.imshow("BASE", base)
cv2.imshow("BLACKENED", img)
cv2.imshow("CLOSED", close)
cv2.imshow("RESULT", result)
cv2.waitKey(0)

# write results to disk
cv2.imwrite("dots_blackened.png", img)
cv2.imwrite("dots_closed.png", close)
cv2.imwrite("dots_clusters.png", result)


Base Image with transparency blackened:

enter image description here

Morphology Close Image:

enter image description here

Contours on base image:

enter image description here

Upvotes: 2

Related Questions