Advertisement
Guest User

Untitled

a guest
Apr 7th, 2025
55
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.41 KB | None | 0 0
  1. import cv2
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4.  
  5. # Read the image
  6. image = cv2.imread("image.png")
  7. gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
  8.  
  9. # Perform connected components analysis
  10. num_labels, labels_im = cv2.connectedComponents(gray)
  11.  
  12. # Create a copy of the original image for drawing
  13. result_image = image.copy()
  14.  
  15. # Perform corner detection for each connected component
  16. for label in range(1, num_labels):  # Start from 1 to skip the background
  17.     # Create a mask for the current component
  18.     component_mask = np.uint8(labels_im == label)
  19.  
  20.     # Apply the mask to the grayscale image
  21.     component_gray = cv2.bitwise_and(gray, gray, mask=component_mask)
  22.  
  23.     # Perform corner detection on the component
  24.     corners = cv2.goodFeaturesToTrack(component_gray, 1, 0.01, 10)
  25.  
  26.     M = cv2.moments(component_mask)
  27.     cX = int(M["m10"] / M["m00"])
  28.     cY = int(M["m01"] / M["m00"])
  29.     if corners is not None:
  30.         corners = np.int0(corners)
  31.         for corner in corners:
  32.             x, y = corner.ravel()
  33.             cv2.arrowedLine(result_image, (cX, cY), (x, y), (0, 255, 0), 3)
  34.  
  35. # Display the result
  36. plt.figure(figsize=(12, 6))
  37. plt.subplot(121), plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), plt.title(
  38.     "Original Image"
  39. )
  40. plt.subplot(122), plt.imshow(cv2.cvtColor(result_image, cv2.COLOR_BGR2RGB)), plt.title(
  41.     "Corners Detected"
  42. )
  43. plt.tight_layout()
  44. plt.show()
  45.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement