Two possibilities, of which one is mentioned in your answer and the comment by @miki
- Square center
You do not need to implement your own distance function. SciPy already has a few. For example your euclidean distance in scipy.spatial.distance.euclidean
:
from scipy.spatial import distance
distance.euclidean((x0, y0), (x1, y1))
No need to reinvent the wheel.
- Square edges
In the following example it can be argued whether the red or the blue square are closer to the center. By euclidean distance, it is the blue one. The red one is overlapping the center, though.

If you wanted to have the square with the closest pixel to the center, you could do something like
square = (upper_left_x, upper_left_y, lower_right_x, lower_right_y)
center = (x, y)
if upper_left_x <= x <= lower_right_x and upper_left_y <= y <= lower_right_y:
return 0 # point in square
elif upper_left_x <= x <= lower_right_x: # on vertical line
return min(upper_left_y -y, lower_right_y - y)
elif upper_left_y <= y <= lower_right_y: # on horizontal line
return min(upper_left_x -x, lower_right_x - x)
else:
points = []
for x in (upper_left_x, lower_right_x):
for y in (upper_left_y, lower_right_y):
points.append((x,y))
return min([distance.euclidean((x,y), p) for p in points])
Original answer before edit to question
You can split this up:
- import image
- find the squares
- find the corners
- connect them
- compute distance to image center
The main point here may be any of them (except for 1.2 probably).
There is a neat OpenCV Python tutorial, which tells you how to do some of that. Let us start:
import
import cv2
img = cv2.imread('L3h9H.png')
imports the image.
To see that you imported correctly, you can use
from matplotlib import pyplot as plt
plt.imshow(img, cmap = 'gray', interpolation = 'bicubic')
plt.xticks([]), plt.yticks([]) # to hide tick values on X and Y axis
plt.show()
which shows it to you.
import numpy as np
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
gray = np.float32(gray)
dst = cv2.cornerHarris(gray, 2,3,0.04)
for i, valx in enumerate(dst):
for j, valy in enumerate(valx):
if valy > 0:
print '%s, %s: %s' % (i, j, valy)
Finds corner using one of the built-in algorithms. The corners are listed afterwards.
Next steps would be:
- compute lines between corners (maybe).
- Show min distance of line to image center.
Say if you need more help.