Created
August 28, 2019 13:21
-
-
Save zelinskiy/8c179b2a73e56bbd7d05d30824b20ed0 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import cv2 | |
import numpy as np | |
from math import sin, cos, pi, sqrt | |
import random as rand | |
from time import time | |
def drawCuttedEllipse(frame, ellipse, cut_coeff, color): | |
(cx, cy), (a, b), angle = ellipse | |
if a > b: | |
a, b = b, a | |
a, b = int(a / 2), int(b / 2) | |
dx, dy = cx - b, cy - b | |
ineq1 = lambda x, y: (x * cos(angle) + y * sin(angle)) ** 2 / b ** 2 \ | |
+ (x * sin(angle) - y * cos(angle)) ** 2 / a ** 2 <= 1 | |
ineq2 = lambda x, y: x * cos(angle) + y * sin(angle) <= 2 * b * cut_coeff - b | |
h, w, _ = frame.shape | |
for y in range(dy, (dy + b * 2) % h): | |
for x in range(dx, (dx + b * 2) % w): | |
if ineq1(x - cx, y - cy) and ineq2(x - cx, y - cy) and x < w and y < h: | |
frame[y, x] = color | |
def cuttedEllipseContour(ellipse, cut_coeff, resolution=5): | |
(cx, cy), (a, b), angle = ellipse | |
if a > b: | |
a, b = b, a | |
a, b = int(a / 2), int(b / 2) | |
dx, dy = cx - b, cy - b | |
eq1 = lambda x, y: (x * cos(angle) + y * sin(angle)) ** 2 / b ** 2 \ | |
+ (x * sin(angle) - y * cos(angle)) ** 2 / a ** 2 | |
ineq2 = lambda x, y: x * cos(angle) + y * sin(angle) <= 2 * b * cut_coeff - b | |
acc = [] | |
for y in range(dy, (dy + b * 2), resolution): | |
for x in range(dx, (dx + b * 2)): | |
if 0.99 <= eq1(x - cx, y - cy) <= 1.01 and ineq2(x - cx, y - cy): | |
acc.append((x, y)) | |
break | |
for y in range(dy, (dy + b * 2), resolution): | |
for x in range(dx, (dx + b * 2))[::-1]: | |
if 0.99 <= eq1(x - cx, y - cy) <= 1.01 and ineq2(x - cx, y - cy): | |
acc.append((x, y)) | |
break | |
return cv2.convexHull(np.array(acc).reshape((-1,1,2)).astype(np.int32)) | |
rot = 0 | |
while True: | |
rot += 0.01 | |
rot %= 2 | |
angle = rot * pi | |
mask = np.full((700, 1000, 3), (0, 0, 0), np.uint8) | |
ellipse = (700, 500), (200, 100), angle | |
t0 = time() | |
ctr1 = cuttedEllipseContour(ellipse, 0.8) | |
print(time() - t0) | |
cv2.drawContours(mask, [ctr1], -1, (255, 255, 255), -1) | |
cv2.imshow('frame', mask) | |
if cv2.waitKey(0) & 0xFF == ord('q'): | |
break | |
cv2.waitKey(0) | |
cv2.destroyAllWindows() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment