Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import argparse
- import cv2 as cv
- import numpy as np
- parser = argparse.ArgumentParser(description="Find bright spots in an image.")
- parser.add_argument("image_path", help="path of the image file.")
- parser.add_argument("--threshold", type=int, default=0,
- help="Threshold for binary threshold. Set to 0 to use"
- " automatic thresholding.")
- parser.add_argument("--contour-area-lower-bound", type=int, default=0.01,
- help="lower bound for contour area.")
- parser.add_argument("--contour-area-upper-bound", type=int, default=100,
- help="upper bound for contour area.")
- parser.add_argument("--arc-length-lower-bound", type=int, default=0,
- help="lower bound for contour arc length.")
- parser.add_argument("--arc-length-upper-bound", type=int, default=80,
- help="upper bound for contour arc length.")
- parser.add_argument("--contour-color",
- choices=["red", "green", "blue", "black", "white"],
- default="red",
- help="color of the contours.")
- parser.add_argument("--contour-thickness", type=int, default=2,
- help="thickness of the contour.")
- args = parser.parse_args()
- image = cv.imread(args.image_path)
- cv.imshow("Image", image)
- print("Press key to continue...")
- cv.waitKey(0)
- image_gray = cv.cvtColor(image, cv.COLOR_RGB2GRAY)
- image_blurred = cv.GaussianBlur(image_gray, (11, 11), 0)
- if args.threshold == 0:
- # Automatic thresholding with Otsu's method
- threshold, mask = cv.threshold(image_gray, 0, 255,
- cv.THRESH_BINARY+cv.THRESH_OTSU)
- else:
- threshold, mask = cv.threshold(image_gray, args.threshold, 255,
- cv.THRESH_BINARY)
- cv.imshow("Image", mask)
- print("\nThresholded image")
- print("Press key to continue...")
- cv.waitKey(0)
- _, contours, hierarchy = cv.findContours(mask, cv.RETR_TREE,
- cv.CHAIN_APPROX_SIMPLE)
- print("\nFound {} contours.".format(len(contours)))
- def filter_contour(contour):
- area = cv.contourArea(contour)
- arc_length = cv.arcLength(contour, closed=True)
- return (area > args.contour_area_lower_bound
- and area < args.contour_area_upper_bound
- and arc_length > args.arc_length_lower_bound
- and arc_length < args.arc_length_upper_bound)
- filtered_contours = list(filter(filter_contour, contours))
- # Set color
- if args.contour_color == "red":
- color = (0, 0, 255)
- elif args.contour_color == "green":
- color = (0, 255, 0)
- elif args.contour_color == "blue":
- color = (255, 0, 0)
- elif args.contour_color == "black":
- color = (0, 0, 0)
- elif args.contour_color == "white":
- color = (255, 255, 255)
- cv.drawContours(image, filtered_contours, -1, color, args.contour_thickness)
- cv.imshow("Image", image)
- print("Found {} spots.".format(len(filtered_contours)))
- print("Press key to exit...")
- cv.waitKey(0)
Add Comment
Please, Sign In to add comment