I follow this question:
How can I sort the outlines from left to right and top to bottom?
Sort outlines from left to right and top to bottom. However, my outlines can be found with this (OpenCV 3):
im2, contours, hierarchy = cv2.findContours(threshold,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
and they are formatted like this:
array([[[ 1, 1]], [[ 1, 36]], [[63, 36]], [[64, 35]], [[88, 35]], [[89, 34]], [[94, 34]], [[94, 1]]], dtype=int32)]
When i run the code
max_width = max(contours, key=lambda r: r[0] + r[2])[0] max_height = max(contours, key=lambda r: r[3])[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0]))
I get an error
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
so I changed this to this:
max_width = max(contours, key=lambda r: np.max(r[0] + r[2]))[0] max_height = max(contours, key=lambda r: np.max(r[3]))[3] nearest = max_height * 1.4 contours.sort(key=lambda r: (int(nearest * round(float(r[1])/nearest)) * max_width + r[0]))
but now I get the error:
TypeError: only length-1 arrays can be converted to Python scalars
EDIT:
After reading the answer below, I changed my code:
EDIT 2
This is the code I use to “expand” characters and find outlines
kernel = cv2.getStructuringElement(cv2.MORPH_RECT,(35,35))
End of editing 2
im2, contours, hierarchy = cv2.findContours(dilation,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) myContours = []
Contours before sorting:
[(1, 1, 94, 36), (460, 223, 914, 427), (888, 722, 739, 239), (35,723, 522, 228), (889, 1027, 242, 417), (70, 1028, 693, 423), (1138, 1028, 567, 643), (781, 1030, 98, 413), (497, 1527, 303, 132), (892, 1527, 168, 130), (37, 1719, 592, 130), (676, 1721, 413, 129), (1181, 1723, 206, 128), (30, 1925, 997, 236), (1038, 1929, 170, 129), (140, 2232, 1285, 436)]
Contours after sorting:
( NOTE: This is not the order in which I want to sort the outlines. See the image below.)
[(1, 1, 94, 36), (460, 223, 914, 427), (35, 723, 522, 228), (70,1028, 693, 423), (781, 1030, 98, 413), (888, 722, 739, 239), (889, 1027, 242, 417), (1138, 1028, 567, 643), (30, 1925, 997, 236), (37, 1719, 592, 130), (140, 2232, 1285, 436), (497, 1527, 303, 132), (676, 1721, 413, 129), (892, 1527, 168, 130), (1038, 1929, 170, 129), (1181, 1723, 206, 128)]
The image I'm working with

I want to find the contours in the following order: 
The dilatation image used to find the contours 