# -*- coding: UTF-8 -*-
import datetime
import cv2
import numpy as np
import os
def get_convexHull(src2):
h,w=src2.shape[:2]
gray = cv2.cvtColor(src2, cv2.COLOR_BGR2GRAY)
# Two valued
ret, binary = cv2.threshold(gray, 125, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
# Get structure elements
k = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
# Open operation
binary = cv2.morphologyEx(binary, cv2.MORPH_OPEN, k)
cv2.imshow("binary", binary)
# Contour discovery
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
# Is it a convex hull
ret = cv2.isContourConvex(contours[c])
if not ret:
# Convex hull detection
points = cv2.convexHull(contours[c])
hull_area = cv2.contourArea(points)
if hull_area<100*100:
continue
if hull_area>(0.3*w*h):
continue
total = len(points)
for i in range(len(points)):
x1, y1 = points[i % total][0]
x2, y2 = points[(i + 1) % total][0]
# cv2.circle(src2, (x1, y1), 4, (255, 0, 0), 2, 8, 0)
cv2.line(src2, (x1, y1), (x2, y2), (0, 0, 255), 2, 8, 0)
print("convex : ", ret)
# Show
cv2.imshow("contours_analysis", src2)
cv2.waitKey(1)
cap = cv2.VideoCapture(0)
cap.set(3, 1080)
cap.set(4, 1920)
count = 0
ok_count = 0
need_save = False
f_index = 0
time_today = datetime.datetime.now().strftime('/%m%d/')
target_dir="capture"
target_dir = target_dir + time_today+"img_o/"
os.makedirs(target_dir,exist_ok=True)
while True:
ret, img_raw = cap.read()
f_index+=1
if img_raw is not None:
img_raw = img_raw[50:(img_raw.shape[0] - 50), 100:(img_raw.shape[1] - 100)]
img_raw=cv2.flip(img_raw,1)
get_convexHull(img_raw.copy())
Fit polygon , Polygons may have holes , The convex hull is closest to the outer contour :
epsilon = 0.02 * cv2.arcLength(contours[c], True)
approx = cv2.approxPolyDP(contours[c], epsilon, True)
cv2.drawContours(src2, [approx], -1, (255, 0, 100), 3) # If “approx” Don't add “[ ]” What you draw is the fitted points