filtered = [cnt for cnt in contours if cv2.contourArea(cnt) > min_area]
# List to hold merged contours
merged_contours = []
used = [False] * len(filtered)
for i in range(len(filtered)):
if not used[i]:
# Create a new contour that will be merged
merged = filtered[i]
used[i] = True
for j in range(i + 1, len(filtered)):
if not used[j]:
# Check bounding box distance
bbox1 = cv2.boundingRect(merged)
bbox2 = cv2.boundingRect(filtered[j])
dist = np.sqrt((bbox1[0] - bbox2[0])**2 + (bbox1[1] - bbox2[1])**2)
if dist < 50: # Distance threshold for merging
merged = np.vstack((merged, filtered[j]))
used[j] = True
merged_contours.append(cv2.convexHull(merged))
return merged_contours
Info
Name
Toukir sabugar
Python Version
Description
AI ------------------------------
import cv2 import numpy as np import matplotlib.pyplot as plt from ultralytics import YOLO
def predict_on_image(model, img, conf): result = model(img, conf=conf)[0]
def overlay(image, mask, color, alpha): color = color[::-1]
Ensure colored_mask has the same number of dimensions as image
def draw_bounding_boxes(image, boxes, color): for box in boxes: x1, y1, x2, y2 = map(int, box) cv2.rectangle(image, (x1, y1), (x2, y2), color, 2)
def filter_and_merge_contours(contours, min_area=100):
Filter contours by area
Load the model
model = YOLO('yolov8n-seg.pt')
Load the image using OpenCV
img_path = '/content/20240713_194215.jpg' img = cv2.imread(img_path)
Check if the image was loaded successfully
if img is None: raise ValueError(f"Image at path '{img_path}' could not be loaded. Please check the path and try again.")
Predict using YOLOv8
boxes, masks, cls, probs = predict_on_image(model, img, conf=0.4)
if masks is not None: # Check if masks were returned
Overlay masks on the original image
else: print("No masks detected.")
Non_AI ---------------
import cv2 import numpy as np import matplotlib.pyplot as plt
image = cv2.imread('/content/20240713_194215.jpg') gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) plt.imshow(gray, cmap='gray');
blur = cv2.GaussianBlur(gray, (11,11), 0) plt.imshow(blur, cmap='gray')
canny = cv2.Canny(blur, 90, 200, 3) plt.imshow(canny, cmap='gray')
dilated = cv2.dilate(canny, (1,1), iterations = 22) plt.imshow(dilated, cmap='gray')
(cnt, heirarchy) = cv2.findContours(dilated.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) cv2.drawContours(rgb, cnt, -1, (0,255,0), 2)
plt.imshow(rgb)
print('items in the image: ', len(cnt)) plt.show()
Additional Comments