explain the method used fot this code import cv2 import numpy as np import…
- User
explain the method used fot this code
import cv2 import numpy as np import matplotlib.pyplot as plt
Read the image
src = cv2.imread('/Users/abhi/Downloads/Zerodur/Sample 8_Fine.tif') imgray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
Blur the image to suppress artefacts
in the binary image while preserving edges
median = cv2.medianBlur(imgray, 15)
Do a global thresholding
ret, thresh = cv2.threshold(median, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
Morphological operations to reduce noise
kernel = np.ones((5, 5), np.uint8) opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel, iterations=1) closing = cv2.morphologyEx(opening, cv2.MORPH_CLOSE, kernel, iterations=1)
Copy image to show binary image (findContours manipulates source)
copy = closing.copy()
Detect just external contours
contours, hierarchy = cv2.findContours(copy, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) height, width, channels = src.shape
Image for displaying contour
drawing = np.zeros((height, width, 3), dtype='uint8')
Variable to store the largest circle contour
largest_circle_contour = None largest_circle_area = 0
Loop through contours to find the largest one
for contour in contours: # Check if the contour has at least 5 points if len(contour) >= 10: # Calculate the area of the contour area = cv2.contourArea(contour)
# Calculate the circularity of the contour perimeter = cv2.arcLength(contour, True) circularity = 4 * np.pi * (area / (perimeter ** 2)) if perimeter > 0 else 0 # Check if the contour is circular enough and has a larger area if circularity > 0.1 and area > largest_circle_area: ########### Adjust circularity threshold as needed ############# largest_circle_contour = contour largest_circle_area = areaDraw the largest circle contour if found
if largest_circle_contour is not None: cv2.drawContours(drawing, [largest_circle_contour], 0, (255, 0, 0), 2) (x, y), radius = cv2.minEnclosingCircle(largest_circle_contour) center = (int(x), int(y)) cv2.circle(drawing, center, int(radius), (0, 0, 255), 2) try: ellipse = cv2.fitEllipse(largest_circle_contour) # Check if the ellipse parameters are valid if ellipse[1][0] > 0 and ellipse[1][1] > 0: cv2.ellipse(drawing, ellipse, (0, 255, 0), 2) else: print("Invalid ellipse parameters:", ellipse) except Exception as e: print("Error fitting ellipse:", e)
Convert images from BGR to RGB for matplotlib
src_rgb = cv2.cvtColor(src, cv2.COLOR_BGR2RGB) median_rgb = cv2.cvtColor(median, cv2.COLOR_GRAY2RGB) thresh_rgb = cv2.cvtColor(thresh, cv2.COLOR_GRAY2RGB) opening_rgb = cv2.cvtColor(opening, cv2.COLOR_GRAY2RGB) closing_rgb = cv2.cvtColor(closing, cv2.COLOR_GRAY2RGB) drawing_rgb = cv2.cvtColor(drawing, cv2.COLOR_BGR2RGB)
- Assistant