Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import cv2
- import numpy as np
- def process_blob(n, contour, input_img, output_img):
- MAJOR_DEFECT_THRESHOLD = 2.0
- cv2.drawContours(output_img, [contour], 0, (191,0,0), 2)
- hull = cv2.convexHull(contour)
- cv2.drawContours(output_img, [hull], 0, (0,191,0), 2)
- hull_idx = cv2.convexHull(contour, returnPoints=False)
- defects = cv2.convexityDefects(contour, hull_idx)
- intersections = []
- for i,defect in enumerate(np.squeeze(defects, 1)):
- first_idx, last_idx, far_idx, far_dist = defect
- real_far_dist = far_dist / 256.0
- if real_far_dist >= MAJOR_DEFECT_THRESHOLD:
- print(("DEFECT #%d " % i), first_idx, last_idx, far_idx, real_far_dist)
- intersections.append(far_idx)
- if len(intersections) == 0:
- print("One ellipse")
- ellipse = cv2.fitEllipse(contour)
- cv2.ellipse(output_img, ellipse, (0,0,255), 2)
- return [ellipse]
- if len(intersections) == 4:
- print("Two ellipses")
- contour_segments = [
- contour[intersections[0]:intersections[1]+1]
- , contour[intersections[1]:intersections[2]+1]
- , contour[intersections[2]:intersections[3]+1]
- , np.vstack([contour[intersections[3]:],contour[:intersections[0]+1]])
- ]
- cv2.polylines(output_img, [contour_segments[0]], False, (0,255,0), 4)
- cv2.polylines(output_img, [contour_segments[1]], False, (0,255,255), 4)
- cv2.polylines(output_img, [contour_segments[2]], False, (255,255,0), 4)
- cv2.polylines(output_img, [contour_segments[3]], False, (255,0,255), 4)
- split_contours = [
- np.vstack([contour_segments[0], contour_segments[2]])
- , np.vstack([contour_segments[1], contour_segments[3]])
- ]
- ellipses = [cv2.fitEllipse(c) for c in split_contours]
- for ellipse in ellipses:
- cv2.ellipse(output_img, ellipse, (0,0,255), 2)
- return ellipses
- print("Invalid scenario")
- return []
- image = cv2.imread('input.png', cv2.IMREAD_GRAYSCALE)
- _,img_binary = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY_INV)
- contours, _ = cv2.findContours(img_binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
- print("Found %d blob(s)." % len(contours))
- PADDING = 20
- for i,contour in enumerate(contours):
- orig_x, orig_y, width, height = cv2.boundingRect(contour)
- offset_x, offset_y = orig_x - PADDING, orig_y - PADDING
- offset_contour = contour - (offset_x, offset_y)
- input_img = cv2.copyMakeBorder(image[orig_y:orig_y+height,orig_x:orig_x+width]
- , PADDING, PADDING, PADDING, PADDING, cv2.BORDER_CONSTANT, None, 255)
- #output_img = np.zeros((PADDING * 2 + height, PADDING * 2 + width, 3), np.uint8)
- output_img = cv2.cvtColor(cv2.add(input_img, 127), cv2.COLOR_GRAY2BGR)
- process_blob(i, offset_contour, input_img, output_img)
- cv2.imshow('', output_img)
- cv2.waitKey()
Add Comment
Please, Sign In to add comment