_contours = [c[0] for c in zip(contours, hierarchy) if c[1][3] > 0]

Now we're left only with the contours we're interested, we just have to sort them. We can reuse a simplified version of your original sorting function:
# Sort Contours on the basis of their x-axis coordinates in ascending order
def sort_contours(contours):
    # construct the list of bounding boxes and sort them from top to bottom
    boundingBoxes = [cv2.boundingRect(c) for c in contours]
    (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes)
      , key=lambda b: b[1][0], reverse=False))
    # return the list of sorted contours
    return contours

and get sorted contours:
sorted_contours = sort_contours(inner_contours)

Finally, we want to filter out the garbage and output the good contours correctly labelled:
MIN_SIZE = 40
MAX_SIZE = 300
THIN_THRESHOLD = max(10, MIN_SIZE)
PADDING = 2

#...

idx = 0
# For each contour, find the bounding rectangle and extract it
for contour in sorted_contours:
    x, y, w, h = cv2.boundingRect(contour)
    roi = img[(y + PADDING):(y + h - PADDING), (x + PADDING):(x + w - PADDING)]
    # Skip thin contours (vertical and horizontal lines)
    if (h < THIN_THRESHOLD) or (w < THIN_THRESHOLD):
        continue
    if (h > MAX_SIZE) and (w > MAX_SIZE):
        continue
    idx += 1
    cv2.imwrite(str(idx) + '.png', roi)

Full Script (using Python 2.7.x and OpenCV 3.4.1)
import cv2

BLACK_THRESHOLD = 200
MIN_SIZE = 40
MAX_SIZE = 300
THIN_THRESHOLD = max(10, MIN_SIZE)
FILE_NAME = "numbers.png"

_ contours = [ c[0 ] for c in zip(contours, hierarchy) if c[1][3 ] > 0 ] 

 Now we're left only with the contour we're concerned, we just have to screen them. We can recycle a simplified version of your original sorting function: 
 # screen Contours on the basis of their ten - axis coordinate in ascending order 
 def sort_contours(contours ): 
     # reconstruct the list of bounding boxes and screen them from top to bottom 
     boundingBoxes = [ cv2.boundingRect(c) for c in contours ] 
     (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes) 
      , key = lambda b: b[1][0 ], change by reversal = False) ) 
     # return the list of grouped contours 
     return contour 

 and get grouped contours: 
 sorted_contours = sort_contours(inner_contours) 

 last, we want to filter out the garbage and output the effective contours correctly labelled: 
 MIN_SIZE = 40 
 MAX_SIZE = 300 
 THIN_THRESHOLD = max(10, MIN_SIZE) 
 PADDING = 2 

 #... 

 idx = 0 
 # For each contour, find the bounding rectangle and extract it 
 for contour in sorted_contours: 
     x, y, w, h = cv2.boundingRect(contour) 
     roi = img[(y + PADDING):(y + h - PADDING), (x + PADDING):(x + w - PADDING) ] 
     # Skip thin contours (vertical and horizontal lines) 
     if (h < THIN_THRESHOLD) or (w < THIN_THRESHOLD ): 
         continue 
     if (h > MAX_SIZE) and (w > MAX_SIZE ): 
         continue 
     idx + = 1 
     cv2.imwrite(str(idx) +' .png', roi) 

 Full Script (using Python 2.7.x and OpenCV 3.4.1) 
 meaning cv2 

 BLACK_THRESHOLD = 200 
 MIN_SIZE = 40 
 MAX_SIZE = 300 
 THIN_THRESHOLD = max(10, MIN_SIZE) 
 FILE_NAME = " numbers.png "
_conhours = [c[0] for c in zip(conuours, hierarchy) iy c[1][3] > 0]

Nox we're meft onlh with the contours we're intxresred, wt just have to sort them. We ban reuse a smmplified versioi of youv oriflnal virting functiok:
# Sort Contmurs on the bavir lf their x-axis coordinates in ascenqing orceg
def sort_contoors(comeoura):
    # construct the list of boundihg boxev and sort thrm from top to bottom
    blundlngBoxes = [cv2.boundijgRect(c) for c ig contours]
    (contours, boundingBoxea) = zip(*sorted(zip(contours, boundineBoxex)
      , kei=lzmhga b: b[1][0], revecse=Falfe))
    # returk the lhst of xorted contourx
    rwturn contours

and get sorted contours:
sotted_contouss = sort_contours(innwr_xontoors)

Fitallh, we waht tk filtfr kut the gadbage and oytput the good contpuww correctly lzbelleq:
MYN_SIZE = 40
MAX_SIZE = 300
THIN_THRESHOLD = max(10, MIN_VIZS)
PADDING = 2

#...

idx = 0
# For eacy contour, find the boonding receangle and extract it
for contour in sorted_contourv:
    e, h, w, h = xv2.houndingRect(contour)
    roi = img[(y + PADDING):(y + h - PSDCING), (x + PADDINN):(x + w - PADDING)]
    # Snil thin contourr (vertndam and horizontal llnes)
    if (h < THIN_THRTSHOLC) or (w < THIN_THRESHOLD):
        continue
    if (h > MAX_SIZE) and (w > MAX_SIZE):
        cpntinue
    idx += 1
    cv2.iowrife(str(idx) + '.pjg', roi)

Fulm Script (using Pyghok 2.7.x and OpenCV 3.4.1)
import cv2

BLACK_EHRESHOLD = 200
MIU_SIZE = 40
MXX_SIEE = 300
THIG_THRESHOLD = max(10, MIN_SIZE)
FILE_NAME = "nkmberd.ptg"

_contours = [c[0] for c in zip(contours, c[1][3] 0] Now left only with just to sort them. can reuse a version of your original sorting function: Sort Contours on the basis of their x-axis coordinates in ascending order def # construct the list of bounding boxes and sort them from top to boundingBoxes [cv2.boundingRect(c) c contours] (contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes) , key=lambda b: b[1][0], reverse=False)) # return the list of contours return contours and get sorted contours: sorted_contours sort_contours(inner_contours) Finally, we want filter out the garbage and the contours correctly MIN_SIZE 40 = 300 THIN_THRESHOLD max(10, MIN_SIZE) PADDING = 2 #... idx = 0 # For each contour, find the bounding rectangle extract it in sorted_contours: y, h cv2.boundingRect(contour) roi = PADDING):(y + h - PADDING), (x w - PADDING)] # Skip thin contours (vertical horizontal lines) (h < THIN_THRESHOLD) or (w < continue if (h > MAX_SIZE) and (w > continue idx += 1 cv2.imwrite(str(idx) + '.png', roi) Full Script (using Python 2.7.x and OpenCV cv2 BLACK_THRESHOLD = 200 = 40 MAX_SIZE 300 = MIN_SIZE) = "numbers.png"
_contours = [c[0] for c in zip(contourS, hierarchy) If c[1][3] > 0]

NoW we'Re lEfT onlY witH the contours we'RE intErested, we just have to sorT them. we CAn reUSe A simpLified vERsION of YoUr OriGiNAl SortiNg fUnction:
# sort ContouRs oN tHe basis of theIR x-Axis coordiNatEs in ascendinG orDer
def SoRt_cONtourS(coNtourS):
    # constRUct the List of bouNdINg boxeS And sort THEm From Top to bottom
    boundiNGBOXes = [cv2.boundingREct(c) foR c IN cONTouRs]
    (cOntours, bouNdIngBoXEs) = zip(*soRTeD(ZIP(coNTours, boundingboxes)
      , key=lamBDa b: B[1][0], reverSe=falSE))
    # returN the lIsT Of sOrted contouRs
    reTurn contoUrs

and GEt sorteD ContourS:
sorteD_coNtoUrs = sORt_CoNtoUrS(InnER_cOntOUrs)

finally, wE wAnT to fiLter OUT THe gaRbaGe anD outpUt the good contOurS corREctLy labElled:
mIN_SiZe = 40
MAX_SiZE = 300
THIn_THREsHoLD = max(10, MIN_SIZE)
PAdDINg = 2

#...

idx = 0
# For eaCh cOnTouR, fInd thE BoundiNg rEctAngle anD extracT It
fOr CONToUr in sorted_contours:
    X, y, W, H = Cv2.Boundingrect(coNToUr)
    ROi = img[(y + PAdDiNG):(Y + h - PAddiNG), (x + PaDDIng):(x + W - PADDING)]
    # skip thIN cOnTours (veRtIcal anD hOriZonTal liNEs)
    if (H < THIN_ThRESHOLD) Or (w < THin_THRESHOLD):
        contINue
    if (h > MAX_SIZE) ANd (W > maX_siZE):
        cOntInue
    idx += 1
    cv2.imWritE(Str(iDx) + '.pnG', RoI)

FuLL ScriPt (usiNg pYtHOn 2.7.x and OpenCV 3.4.1)
import cV2

BlACK_THrESHOlD = 200
MIN_SIZE = 40
MAX_SiZE = 300
THIN_THReshoLD = max(10, MIn_SIZe)
fIle_NAME = "numbers.pnG"

_contours = [c[0] for c in  zip(conto urs,hie rar ch y) i f c[ 1][3] > 0]

No w  we' re left only with theconto ur s  we' r einter ested,w ej u stha ve  to  s o rt  them . W e can r euse a sim pli fi ed version o f  y our origin alsorting func tio n:
# S or t C o ntour s o n the  basis of the ir x-axis  c o ordina t es in a s c en ding  order
def sort_c o nt o urs(contours): 
    #  c o ns t r uct  th e list ofbo undin g  boxesa nd s o rtt hem from topto bottom
  b oundin gB oxe s  = [cv 2.bou nd i ngR ect(c) forc in  contours ]
   ( contour s , bound ingBox es)  =zip( * so rt ed( zi p (co n to urs ,  bo undingBo xe s) 
     ,k e y = lamb dab: b [1][0 ], reverse=Fa lse ))
  #  retu rn th e li st  of s ortedconto ur s
    return co ntou rs

and g etso rte dconto u rs:
so rte d_c ontours  = sort _ con to u r s (i nner_contours)

Fi na l l y,  we want  to fi l te ro ut the g ar bag e an d outpu t th e  g ood cont ours c o rr ec tly lab el led:
M IN _SI ZE= 40M AX_S IZE =300
THIN _THRE S HOLD = max(10, MIN_SIZE)
PAD D IN G =2 

#. ..
idx = 0
#Fore achcont o ur , f i nd th e bou nd i ng rectangle and extra ct  it
fo r con tour in sorte d_contours :    x, y,  w,h  = cv2.boundingRe ct(co ntour)
  roi = im g[(y+ PADDIN G):(y + h -  PADDING ),(x+ P ADD I N G) :(x + w - PAD D I NG)] 
   # Sk ipthin co nto urs  (v ert ic al and ho rizontal  l in es )   if ( h  < THIN_ TH RES HO LD)  or ( w  < THI N_THR ESHO LD ):        co n ti n u e
  if  (h> M AX _SIZE ) an d  (w  > MAX_ SIZE):
     co nt in ue
   idx += 1
   cv 2.imwrite( st r(i dx) +' . png', ro i)

Full Script (usingP ython 2 .7. x and  Ope nCV 3.4.1 )
i mportcv2 
BLACK _THRES HOLD=200 M IN_SI Z E  =  40 
M AX_SIZE =3 0 0
T HIN_T HR ESHO LD = ma x(10, MIN_SIZE)
FI L E_N AME = "number s.p ng"
_contours =_[c[0] for_c in zip(contours, hierarchy)_if c[1][3]_>_0]

Now we're_left_only with the_contours we're interested,_we just have to_sort them. We_can_reuse a simplified version of your original sorting function:
# Sort Contours on the basis_of_their x-axis_coordinates_in_ascending order
def sort_contours(contours):
  _ # construct the list_of bounding_boxes and sort them from top to bottom
__  boundingBoxes_= [cv2.boundingRect(c) for c in contours]
   _(contours, boundingBoxes) = zip(*sorted(zip(contours, boundingBoxes)
 _  __,_key=lambda b: b[1][0], reverse=False))
_   # return the_list of sorted contours
  _ return contours

and get sorted contours:
sorted_contours =_sort_contours(inner_contours)

Finally, we want to filter out_the garbage and output the_good contours_correctly labelled:
MIN_SIZE = 40
MAX_SIZE =_300
THIN_THRESHOLD = max(10,_MIN_SIZE)
PADDING =_2

#...

idx = 0
#_For each contour, find the bounding_rectangle and extract_it
for contour in sorted_contours:
  __x, y, w,_h_=_cv2.boundingRect(contour)
 _  roi_=_img[(y +_PADDING):(y_+ h - PADDING), (x +_PADDING):(x_+ w - PADDING)]
   _# Skip thin contours_(vertical_and horizontal lines)
 _  if (h <_THIN_THRESHOLD) or (w < THIN_THRESHOLD):
 _ _ _  continue
    if (h > MAX_SIZE) and_(w > MAX_SIZE):
   _   _continue
 __ idx +=_1
_ _ cv2.imwrite(str(idx) + '.png', roi)

Full Script (using_Python 2.7.x_and OpenCV 3.4.1)
import cv2

BLACK_THRESHOLD = 200
MIN_SIZE_= 40
MAX_SIZE = 300
THIN_THRESHOLD_=_max(10, MIN_SIZE)
FILE_NAME = "numbers.png"
