# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import numpy as np
import cv2 as cv

src = cv.imread('data_hierarchy3.png')
maxSizeOfOriginalSrcImg = max(src.shape[0], src.shape[1])
src = cv.resize(src, (0,0), fx=1000/maxSizeOfOriginalSrcImg, fy=1000/maxSizeOfOriginalSrcImg) 
reDrewnLine = src.copy()

# re-draw  all edges
gray = cv.cvtColor(reDrewnLine, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,0,255)
contours1, hierarchy1 = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)
cv.drawContours(reDrewnLine, contours1, -1, (0,0,0), 3)

# get contours by re-draw edges
gray = cv.cvtColor(reDrewnLine, cv.COLOR_BGR2GRAY)
edges = cv.Canny(gray,0,255)
contours1, hierarchy1 = cv.findContours(edges, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

# hierarchy [Next, Previous, First_Child, Parent]
print(len(contours1))
print(contours1[0])
print(contours1[0] + 1)

copy = src.copy()
cv.drawContours(copy, contours1, -1, (0,0,0), 1)
currentRootIndex = -1
rootRegions = {}
for i,cnt in enumerate(contours1):
    x,y,w,h = cv.boundingRect(cnt)
    print(i, hierarchy1[0][i])
    if hierarchy1[0][i][3] == -1:
        # root region
        currentRootIndex = i + 1
        if currentRootIndex == len(contours1):
            break
        rootRegion = {'index': i, 'contour': cv.contourArea(contours1[currentRootIndex]), 'childRegion': []}
        rootRegions[currentRootIndex] = rootRegion
    elif hierarchy1[0][i][3] == currentRootIndex:
        rootRegions[currentRootIndex]['childRegion'].append({'index': i, 'contour': cv.contourArea(cnt)})
        
print(rootRegions)        
data2 = json.dumps(rootRegions, sort_keys=True, indent=4, separators=(',', ': '))
print(data2)
    
#     cv.putText(copy, str(i), (x+5,y+10), cv.FONT_HERSHEY_PLAIN, 1,(0,0,0), 1, cv.LINE_AA)

# for i,cnt in enumerate(contours2):    
# #     print(cnt)
#     mask = np.zeros(copy.shape, np.uint8)
#     mask = cv.fillConvexPoly(mask, cnt, (255, 255, 255))
#     grayMask = cv.cvtColor(mask, cv.COLOR_BGR2GRAY)
#     masked = cv.bitwise_and(gray, grayMask)
#     cv.imshow('mask' + str(i), masked)
    
# #     edges = cv.Canny(masked,0,255)
#     contours3, hierarchy3 = cv.findContours(masked, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# #     maskedCopy = masked.copy()
# #     cv.drawContours(maskedCopy, contours3, -1, (255, 255, 255), 2)
#     print(i, len(contours3), hierarchy3)
    
    
    
cv.imshow('copy', copy)
cv.imshow('gray', gray)
cv.imshow('edges', edges)
# cv.imshow('opening', opening)

cv.waitKey(0)
cv.destroyAllWindows()     

StarcoderdataJupyterScriptsDedupFiltered