Tags: miscellaneous 

Rating: 0

# Sight at Last

This is a programming challenge. We're given a server that'll give us some base64 image of a bunch of black circles. We need to find the minimum distance between the centers of these circles. What's more, we need to do this 100 of these in 500 seconds.

This is a quick and dirty script I wrote to handle this:

```python
#!/usr/bin/env python3

import base64
import cv2
import imutils
import math
import socket

def findCenters(image):

pairs = []

img = cv2.imread(image)
img = cv2.copyMakeBorder(img, 10, 10, 10, 10, cv2.BORDER_CONSTANT, value=[255, 255, 255])
grey = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
notted = cv2.bitwise_not(grey)
blurry = cv2.GaussianBlur(notted, (5, 5), 0)
thresh = cv2.threshold(blurry, 60, 255, cv2.THRESH_BINARY)[1]

contours = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
contours = imutils.grab_contours(contours)

for contour in contours:
moment = cv2.moments(contour)
centreX = float(moment["m10"] / moment["m00"])
centreY = float(moment["m01"] / moment["m00"])
pairs.append((centreX, centreY))

return pairs

def calculateMinDistance(pairs):

minimum = 1000000000

for a in pairs:
for b in pairs:
c = ( math.sqrt(
( (a[0] - b[0]) ** 2 ) +
( (a[1] - b[1]) ** 2 ) ) )
if 0 < c < minimum:
minimum = c

return minimum

def get(s):

data = b""

while True:
chunk = s.recv(128)
print(chunk.decode("utf-8"), end="")
data += chunk
if ">" in chunk.decode("utf-8"):
break

return data

def makeImage(data):

base64d = data.split(":\n")[1].split("\n>")[0]
with open("image.jpg", "wb+") as f:
f.write(base64.b64decode(base64d))

def main():

passed = 0

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.connect(("p1.tjctf.org", 8005))
while True:
data = get(s).decode("utf-8")
makeImage(data)
centers = findCenters("image.jpg")
minDist = calculateMinDistance(centers)
print(minDist)
print("Passed: %s\n" % passed)
s.send(("%s\n" % minDist).encode())
passed += 1

if __name__ == "__main__":
main()
```

![](https://raw.githubusercontent.com/shawnduong/ctf-writeups/master/2019-TJ/images/sight-at-last.png)

```
tjctf{15_th1s_c0mput3r_v1si0n?}
```