Files
picar/GestureRecognition/kaleidoscope.py
2020-02-21 21:06:05 +10:30

73 lines
2.4 KiB
Python

import numpy as np
import cv2
def make_triangle(start_img):
h, w, d = start_img.shape
#crop square
inset = int((max(w,h) - min(w,h)) / 2)
# sqrimg = start_img.crop(inset, inset, h-inset, w-inset)
insetW = inset if w > h else 0
insetH = inset if h > w else 0
sqrimg = start_img[insetH:h-insetH, insetW:w-insetW]
#solve equilateral triangle
w, h, d = sqrimg.shape
print((w,h))
mask = np.zeros((w,h,d))
t_height = w/2 * np.tan(60)
pts = np.array([[0,w],[h/2,t_height],[h,w]], np.int32)
pts = pts.reshape((-1,1,2))
mask = cv2.fillPoly(mask, [pts], (255,0,0))
# With mask, get the triangle from the original image.
sqrimg[:,:,0] = np.where(mask[:,:,0] == 255, sqrimg[:,:,0], 0)
sqrimg[:,:,1] = np.where(mask[:,:,0] == 255, sqrimg[:,:,1], 0)
sqrimg[:,:,2] = np.where(mask[:,:,0] == 255, sqrimg[:,:,2], 0)
return sqrimg
def rotate(im, rotation):
M = cv2.getRotationMatrix2D((im.shape[1]/2,im.shape[0]/2),rotation,1)
im[:,:,0] = cv2.warpAffine(im[:,:,0],M,(im.shape[1],im.shape[0]))
im[:,:,1] = cv2.warpAffine(im[:,:,1],M,(im.shape[1],im.shape[0]))
im[:,:,2] = cv2.warpAffine(im[:,:,2],M,(im.shape[1],im.shape[0]))
return im
def make_kaleidoscope(img):
triangle = make_triangle(img)
def make_trapezoid(triangle, save=False):
w, h = triangle.size
can_w, can_h = w*3, h
output = np.array((can_w, can_h, 3))
output = Image.new('RGBA', (can_w, can_h), color=255)
def mirror_paste(last_img, coords):
mirror = rotate(cv2.flip(last_img, 1), 60)
output.paste(mirror, (coords), mirror)
return mirror, coords
#paste in bottom left corner
output.paste(triangle,(0, can_h-h), triangle)
last_img, coords = mirror_paste(triangle, (int(w/4.4), -int(h/2.125)))
last_img, coords = mirror_paste(rotateIm(last_img, 120), (int(can_w/7.3), -228))
output = output.crop((0,15, w*2-22, h))
if save:
path = 'output/trapezoid_{}'.format(filename.split('/')[1])
output.save(path)
return output, path
return output
if __name__ == "__main__":
img = cv2.imread("/Users/piv/Documents/Projects/car/GestureRecognition/IMG_0818.png")
triangle = make_triangle(img)
triangle = cv2.resize(triangle, None, fx=0.3, fy=0.3, interpolation = cv2.INTER_AREA)
triangle = rotate(triangle, 180)
cv2.imshow("", triangle)
cv2.waitKey(0)
cv2.destroyAllWindows()