Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from __future__ import print_function
- import cv2 as cv
- import numpy as np
- import argparse
- import random as rng
- rng.seed(12345)
- def calculate_parameters(contour, gray_image):
- area = cv.contourArea(contour)
- perimeter = cv.arcLength(contour, True)
- x, y, w, h = cv.boundingRect(contour)
- aspect_ratio = float(w) / h
- rect_area = w * h
- extent = float(area) / rect_area
- hull = cv.convexHull(contour)
- hull_area = cv.contourArea(hull)
- solidity = float(area) / hull_area
- equi_diameter = np.sqrt(4 * area / np.pi)
- if len(contour) >= 5:
- (x, y), (MA, ma), angle = cv.fitEllipse(contour)
- else:
- angle = 0
- mask = np.zeros_like(gray_image)
- cv.drawContours(mask, [contour], -1, 255, -1)
- mean_val = cv.mean(gray_image, mask=mask)[0]
- return {
- "Area": area,
- "Perimeter": perimeter,
- "Aspect Ratio": aspect_ratio,
- "Extent": extent,
- "Solidity": solidity,
- "Equivalent Diameter": equi_diameter,
- "Orientation": angle,
- "Mean Intensity": mean_val
- }
- def thresh_callback(val):
- threshold = val
- canny_output = cv.Canny(src_gray, threshold, threshold * 2)
- contours, _ = cv.findContours(canny_output, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
- drawing = np.zeros((canny_output.shape[0], canny_output.shape[1], 3), dtype=np.uint8)
- for i, contour in enumerate(contours):
- color = (rng.randint(0, 256), rng.randint(0, 256), rng.randint(0, 256))
- cv.drawContours(drawing, contours, i, color)
- # Compute and print parameters for each contour
- params = calculate_parameters(contour, src_gray)
- print(f"Contour #{i + 1}:")
- for param_name, param_value in params.items():
- print(f" {param_name}: {param_value}")
- cv.imshow('Contours', drawing)
- parser = argparse.ArgumentParser(description='Code for Creating Bounding boxes and circles for contours tutorial.')
- parser.add_argument('--input', help='Path to input image.', default='water_coins.jpg')
- args = parser.parse_args()
- src = cv.imread(cv.samples.findFile(args.input))
- if src is None:
- print('Could not open or find the image:', args.input)
- exit(0)
- src_gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
- src_gray = cv.blur(src_gray, (3, 3))
- source_window = 'Source'
- cv.namedWindow(source_window)
- cv.imshow(source_window, src)
- max_thresh = 255
- thresh = 100
- cv.createTrackbar('Canny thresh:', source_window, thresh, max_thresh, thresh_callback)
- thresh_callback(thresh)
- cv.waitKey()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement