Skip to content

Commit 7d4e51b

Browse files
committed
Added 1NDVCLUB task
1 parent dbdc2a8 commit 7d4e51b

26 files changed

+309
-0
lines changed

1NDVCLUB_TASK/create/constants.py

+7
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
hosts = "0.0.0.0"
2+
server_port = 5050
3+
input_chunk_size = 2**10
4+
max_users = 1000
5+
pause = 1
6+
socket_timeout = 5
7+
max_size_bytes = 1024 * 1024 * 2

1NDVCLUB_TASK/create/gansta_eye.py

+153
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,153 @@
1+
import cv2
2+
import numpy as np
3+
4+
#WARNING! OpenCV 3.* required.
5+
6+
# Parameters for lucas kanade optical flow
7+
lk_params = dict( winSize = (15,15),
8+
maxLevel = 2,
9+
criteria = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 0.03))
10+
11+
12+
def getHarrisPoints(gray_img):
13+
harris = cv2.cornerHarris(gray_img, 2, 3, 0.05)
14+
# Threshold for an optimal value
15+
xarr,yarr = np.nonzero(harris > 0.03*harris.max())
16+
harrisPointsArray = [np.array([[x,y]]) for x,y in zip(xarr,yarr)]
17+
return np.array(harrisPointsArray, dtype=np.float32)
18+
19+
20+
def getFASTPoints(gray_img):
21+
# Initiate FAST object with default values
22+
fast = cv2.FastFeatureDetector_create(threshold=5)
23+
# find keypoints
24+
kp_array = fast.detect(gray_img,None)
25+
# print kp_array[0].pt[1]
26+
fastPointsArray = [np.array([[kp.pt[0], kp.pt[1]]]) for kp in kp_array]
27+
return np.array(fastPointsArray, dtype=np.float32)
28+
29+
def videoTracking(cap, slow_motion_delay, detector):
30+
# Create some random colors
31+
color = np.random.randint(0,255,(100,3))
32+
# Take first frame and find corners in it
33+
ret, old_frame = cap.read()
34+
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
35+
# Create a mask image for drawing purposes
36+
mask = np.zeros_like(old_frame)
37+
# Define the codec and create VideoWriter object
38+
# height, width, _ = old_frame.shape
39+
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
40+
# out = cv2.VideoWriter('output_'+detector+'.avi',fourcc, slow_motion_delay, (width,height))
41+
if detector == 'Harris':
42+
oldTrackPoints = getHarrisPoints(old_gray)
43+
elif detector == 'FAST':
44+
oldTrackPoints = getFASTPoints(old_gray)
45+
else:
46+
print('Not correct method')
47+
print "$$$ Checking if i can recognise your move, n1ggv"
48+
while not len(oldTrackPoints) and cap.isOpened():
49+
ret, old_frame = cap.read()
50+
old_gray = cv2.cvtColor(old_frame, cv2.COLOR_BGR2GRAY)
51+
oldTrackPoints = getFASTPoints(old_gray)
52+
while cap.isOpened():
53+
ret, frame = cap.read()
54+
track_img = None
55+
if ret:
56+
new_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
57+
# calculate optical flow
58+
newTrackPoints, st, err = cv2.calcOpticalFlowPyrLK(old_gray, new_gray, oldTrackPoints,
59+
None, **lk_params)
60+
61+
# Select good points
62+
if newTrackPoints is not None and len(newTrackPoints):
63+
good_new = newTrackPoints[st==1]
64+
good_old = oldTrackPoints[st==1]
65+
# draw the tracks
66+
for i,(new,old) in enumerate(zip(good_new,good_old)):
67+
a,b = new.ravel()
68+
c,d = old.ravel()
69+
mask = cv2.line(mask, (a,b),(c,d),color[i%len(color)].tolist(), 2) #(255,0,0), 2)
70+
frame = cv2.circle(frame,(a,b),2,color[i%len(color)].tolist(),-1)#(0,255,0),-1)
71+
track_img = cv2.add(frame, mask)
72+
#write tracked frame
73+
# out.write(track_img)
74+
# cv2.imshow('videoTracking '+detector, track_img)
75+
# if cv2.waitKey(slow_motion_delay) & 0xFF == ord('q'):
76+
# break
77+
78+
# Now update the previous frame and previous points
79+
old_gray = new_gray.copy()
80+
oldTrackPoints = good_new.reshape(-1,1,2)
81+
else:
82+
break
83+
return mask
84+
85+
def crop_image(input_img):
86+
sum_rows = np.sum(input_img, axis=0)
87+
nonnull = np.nonzero(sum_rows)[0]
88+
left = nonnull[0]
89+
right = nonnull[len(nonnull)-1]
90+
sum_cols = np.sum(input_img, axis=1)
91+
nonnull = np.nonzero(sum_cols)[0]
92+
low = nonnull[0]
93+
high = nonnull[len(nonnull)-1]
94+
return input_img[low:high,left:right]
95+
96+
97+
def normalize_img(mask_img):
98+
print "$$$ Be good, my beach"
99+
normalized_img = cv2.cvtColor(mask_img, cv2.COLOR_BGR2GRAY)
100+
_,thresh_img = cv2.threshold(normalized_img, 0, 255, cv2.THRESH_BINARY)
101+
kernel = np.ones((5,5),dtype=np.uint8)
102+
dilated_img = cv2.dilate(thresh_img, kernel)
103+
dilated_img = crop_image(dilated_img)
104+
height, width = dilated_img.shape
105+
dilated_img = cv2.resize(dilated_img, (800,1143))
106+
# delta_y = (1143 - dilated_img.shape[0])/2
107+
# delta_y = delta_y if delta_y > 0 else 0
108+
# delta_x = (808 - dilated_img.shape[1])/2
109+
# delta_x = delta_x if delta_x > 0 else 0
110+
# dilated_img = cv2.copyMakeBorder(dilated_img,delta_y,delta_y,delta_x,delta_x,cv2.BORDER_CONSTANT,value=0)
111+
return dilated_img
112+
113+
114+
def detectIt(video, letter):
115+
cap = cv2.VideoCapture(video)
116+
try:
117+
#slow_motion_delay in milliseconds
118+
slow_motion_delay = 80
119+
print "$$$~ Brick Squad Monopoly security ~$$$"
120+
mask_img = videoTracking(cap, slow_motion_delay, 'FAST')
121+
print "$$$ U can't hide u can't run."
122+
cap.release()
123+
cv2.imshow('mask_img', mask_img)
124+
normalized_img = normalize_img(mask_img)
125+
print "$$$ Here we watch ya."
126+
let_symbol = cv2.imread("symbol_{0}.jpg".format(letter))
127+
let_symbol = cv2.cvtColor(let_symbol, cv2.COLOR_BGR2GRAY)
128+
_, let_symbol = cv2.threshold(let_symbol, 0, 255, cv2.THRESH_BINARY_INV)
129+
let_symbol = crop_image(let_symbol)
130+
_,let_symbol = cv2.threshold(let_symbol, 0, 255, cv2.THRESH_BINARY_INV)
131+
#Good size for us
132+
let_symbol = cv2.resize(let_symbol,(800,1143))
133+
# cv2.imshow('let_symbol', let_symbol)
134+
# cv2.imshow('normalized_img', normalized_img)
135+
result_img = cv2.bitwise_and(normalized_img, normalized_img, mask=let_symbol)
136+
# cv2.imshow('result_img', result_img)
137+
# cv2.waitKey(0)
138+
# cv2.destroyAllWindows()
139+
if np.sum(result_img) < 0.15 * 255 * 800 * 1143:
140+
print "$$$ Br0! You are masta!"
141+
return True
142+
print "$$$ Waka Fl0cka doesn't like it! Get the float of the property!"
143+
return False
144+
except:
145+
print "$$$ Get OpenCV 3 or die tryin'."
146+
cap.release()
147+
return False
148+
149+
150+
if __name__ == "__main__":
151+
#Test purposes
152+
filename = "test_L.avi"
153+
detectIt(filename, "L")
+118
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,118 @@
1+
import socket, threading, sys, os
2+
from datetime import datetime
3+
from constants import *
4+
from time import sleep
5+
import gansta_eye
6+
7+
class ClientThread(threading.Thread):
8+
def __init__(self, client_socket, cleint_ip, client_port):
9+
threading.Thread.__init__(self)
10+
self.ip = cleint_ip
11+
self.port = client_port
12+
self.client_socket = client_socket
13+
self.client_socket.settimeout(socket_timeout)
14+
self.id = str(datetime.now()).replace(":", "-").replace(".", "-").replace(" ", "-")
15+
self.dead = False
16+
print "#::New thread started for ({0}, ({1}))".format(str(cleint_ip), str(client_port))
17+
18+
def validate_video(self, video_file, letter):
19+
print "#:: Let's check u..."
20+
return gansta_eye.detectIt(video_file, letter)
21+
22+
def run(self):
23+
print "#{}::Listening for requests.".format(self.id)
24+
target_string = "1NDVCLUB"
25+
validated = 0
26+
for letter in target_string:
27+
print "#::Server is expecting", letter
28+
letter_video = None
29+
video_created = False
30+
client_bytes = "CamStudio"
31+
bytes_received = 0
32+
print "#::Ready to receive..."
33+
while len(client_bytes):
34+
try:
35+
client_bytes = self.client_socket.recv(input_chunk_size)
36+
bytes_received += len(client_bytes)
37+
if bytes_received > max_size_bytes:
38+
raise Exception("#::Too long video. Ain't u a cop?")
39+
if client_bytes and client_bytes != "JustALilByte":
40+
if not video_created: #lazy here
41+
letter_video = open("video_{0}_{1}.avi".format(letter, self.id), 'wb')
42+
video_created = True
43+
letter_video.write(client_bytes)
44+
letter_video.flush()
45+
print "-",
46+
else:
47+
print
48+
if video_created:
49+
print "#::Shiip, it seems your video is over."
50+
letter_video.flush()
51+
letter_video.close()
52+
print "#::video_{0}_{1} is saved.".format(letter, self.id)
53+
else:
54+
print "#::Nothin' from u nothin' from me, baby."
55+
break
56+
except Exception as some_error:
57+
print "#{0}::ERROR({1})".format(self.id, str(some_error))
58+
break
59+
if letter_video is not None:
60+
filename = "video_{0}_{1}.avi".format(letter, self.id)
61+
if self.validate_video(filename, letter):
62+
print "#::Cool, br0!"
63+
validated += 1
64+
os.remove(filename)
65+
print "#::I have removed all da evidence, my little homie. Relax for a while and keep pushin'!"
66+
sleep(pause)
67+
else:
68+
print "#::U've made a mistake. VIP zone ain't for u."
69+
os.remove(filename)
70+
print "#::I do not need your video now, d0ll. I have thrown it away."
71+
break
72+
else:
73+
print "#::No video - no deal. Get out from our hood."
74+
break
75+
if validated == len(target_string):
76+
print "#::Now you are in our club, man. Take your gun."
77+
try:
78+
flag_file = open(".\\test_folder\\flag.txt", "r")
79+
flag = flag_file.readline()
80+
flag_file.close()
81+
print flag
82+
self.client_socket.send(flag)
83+
print "#::Use it as a real gangsta."
84+
except Exception as error:
85+
print "#::Worse for you, baby.", error
86+
else:
87+
print "See ya."
88+
self.client_socket.close()
89+
self.dead = True
90+
return
91+
92+
def main():
93+
out = sys.stdout
94+
host = hosts
95+
port = server_port
96+
server_socket = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM)
97+
server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
98+
server_socket.bind((host, port))
99+
client_threads = []
100+
server_socket.listen(max_users)
101+
while True:
102+
try:
103+
print "\n~~~Listening for incoming connections...(online:" + str(len(client_threads))+ ")\n"
104+
(new_client_socket, (client_ip, client_port)) = server_socket.accept()
105+
client_thread = ClientThread(new_client_socket, client_ip, client_port)
106+
client_thread.start()
107+
client_threads.append(client_thread)
108+
for thread in client_threads:
109+
if thread.dead:
110+
client_threads.remove(thread)
111+
except:
112+
print "~~~About to break..."
113+
break
114+
server_socket.close()
115+
sys.stdout = out
116+
print "~~~PROGRAM OVER"
117+
118+
main()

1NDVCLUB_TASK/create/symbol_1.jpg

8.52 KB
Loading

1NDVCLUB_TASK/create/symbol_B.jpg

14 KB
Loading

1NDVCLUB_TASK/create/symbol_C.jpg

16 KB
Loading

1NDVCLUB_TASK/create/symbol_D.jpg

13.7 KB
Loading

1NDVCLUB_TASK/create/symbol_L.jpg

8.34 KB
Loading

1NDVCLUB_TASK/create/symbol_N.jpg

13.8 KB
Loading

1NDVCLUB_TASK/create/symbol_U.jpg

12.3 KB
Loading

1NDVCLUB_TASK/create/symbol_V.jpg

15 KB
Loading
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
���:
2+
������� ���� ������� ���� ������
3+
��� �������
4+
��� ����������
5+
��������� ��������� �������

1NDVCLUB_TASK/indaclub_full_pack.rar

90.6 KB
Binary file not shown.

1NDVCLUB_TASK/solution/client.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from constants import *
2+
import socket # Import socket module
3+
4+
s = socket.socket() # Create a socket object
5+
server_host = socket.gethostname() # Get local machine name
6+
7+
s.connect((server_host, server_port))
8+
video = open('test_1.avi','r')
9+
chunk = "trvpLord" if video else ""
10+
while chunk:
11+
chunk = video.read(1024)
12+
s.send(chunk)
13+
print 'Sent some part...'
14+
video.close()
15+
print "Done Sending"
16+
s.close

1NDVCLUB_TASK/solution/test_1.avi

16 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_B.avi

390 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_C.avi

15.5 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_D.avi

16.5 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_K.avi

231 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_L.avi

17 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_N.avi

17.5 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_U.avi

20.5 KB
Binary file not shown.

1NDVCLUB_TASK/solution/test_V.avi

17 KB
Binary file not shown.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
1234512339806543
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
����� - �������
2+
��� �� ��� ������ �� �������� ���� �����
3+
� test_folder ��������� ����

1NDVCLUB_TASK/summary.yaml

+6
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
author: 24power & b3ardbear
2+
category:?
3+
description:|
4+
Brick Squuad Monopoly устраивает Trap вечеринку для рэпера Waka Flacka в клубе.
5+
Вы являетесь агентом спецслужб. По предварительным данным, на ней будет проходить огромная подпольная сделка по закупке оружия в VIP зоне.
6+
В целях безопасности Waka Flacka закодил новую систему доступа. Вам необходимо пробраться в клуб и разоблачить коварные планы банды.

0 commit comments

Comments
 (0)