Skip to content

Instantly share code, notes, and snippets.

@RReverser
Created December 3, 2022 23:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RReverser/adafaaa219e86d96c7e2b44b7302e53f to your computer and use it in GitHub Desktop.
Save RReverser/adafaaa219e86d96c7e2b44b7302e53f to your computer and use it in GitHub Desktop.
import cv2
import numpy as np
# Read the image
img = cv2.imread('sky.jpg')
# Convert the image to grayscale
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Use a threshold to detect stars in the image
thresh = cv2.threshold(gray, 240, 255, cv2.THRESH_BINARY)[1]
# Find the contours of the stars
contours = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = contours[0] if len(contours) == 2 else contours[1]
# Loop through the contours and draw a circle around each star
for c in contours:
x,y,w,h = cv2.boundingRect(c)
cv2.circle(img, (x + w // 2, y + h // 2), w // 2, (255, 255, 0), 2)
# Use a brute force matcher to find the nearest stars
bf = cv2.BFMatcher()
# Extract the coordinates of the stars from the contours
star_coords = []
for c in contours:
x,y,w,h = cv2.boundingRect(c)
star_coords.append((x + w // 2, y + h // 2))
# Convert the star coordinates to a numerical array
star_coords = np.array(star_coords, dtype=np.float32)
# Use the numerical array of star coordinates as the query descriptors in the knnMatch() function
matches = bf.knnMatch(star_coords, star_coords, k=2)
# Loop through the matches and connect the nearest stars with lines
for m in matches:
if len(m) == 2:
a, b = m[0], m[1]
# Use the queryIdx and trainIdx attributes of the cv2.DMatch objects to get the indexes of the matched stars
star1_idx = a.queryIdx
star2_idx = b.trainIdx
# Use the indexes to get the coordinates of the matched stars
# Use the indexes to get the coordinates of the matched stars
star1_coord = tuple(map(int, star_coords[star1_idx]))
star2_coord = tuple(map(int, star_coords[star2_idx]))
# Draw a line between the matched stars
# Use the star coordinates as a tuple of coordinates as the first and second arguments to the line() function
cv2.line(img, star1_coord, star2_coord, (0, 255, 0), 2)
# Save the image with the detected constellations
cv2.imwrite('sky_with_constellations.jpg', img)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment