def maxRectContourCrop(img_crop): _, bins = cv.threshold(img_crop, 1, 255, cv.THRESH_BINARY) kernel = np.ones((100, 100), np.uint8) bins = cv.dilate(bins, kernel, iterations=1) bins = cv.erode(bins, kernel, iterations=1) contours, hierarchy = cv.findContours(bins, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE) from maxrect import get_intersection, get_maximal_rectangle coords = coordFinder(contours, img_crop) _, coordinates = get_intersection([coords]) coo = list(coordinates) ll, ur = get_maximal_rectangle(coo) bx = (ll[0], ll[1], ur[0], ur[1]) bx = [round(num) for num in bx] # image = Image.fromarray(processed_image) # img_crop = image.crop(bx) return (bx) #img_crop, bx)
def test_get_maximal_rectangle(): srcpath = os.path.join(os.path.dirname(__file__), 'fixtures/polygon.geojson') with open(srcpath) as src: data = src.read() geojson = json.loads(data) feature = geojson.get('features')[0] coordinates = feature.get('geometry').get('coordinates')[0] ll, ur = maxrect.get_maximal_rectangle(coordinates) expected_ll = [-101.645507812426, 39.222888638556988] expected_ur = [-92.877169942000137, 42.293564192171694] assert abs(expected_ll[0] - ll[0] < EPS) assert abs(expected_ll[1] - ll[1] < EPS) assert abs(expected_ur[0] - ur[0] < EPS) assert abs(expected_ur[1] - ur[1] < EPS)
def maxrect(ctx, polygon, compare): """ Get an approximately maximal area, axis-aligned rectangle for a polygon represented by GeoJSON. """ if polygon == '-': src = click.open_file('-') if not src.isatty(): data = src.read() else: click.echo(ctx.get_usage()) ctx.exit(1) else: with open(polygon, 'r') as src: data = src.read() geojson = json.loads(data) if geojson.get('type') == 'Feature': geojson = { 'type': 'FeatureCollection', 'features': [geojson] } features = geojson.get('features') n_features = len(features) if compare: features = features + copy.deepcopy(features) for feature in features[:n_features]: coordinates = get_maximal_rectangle(feature['geometry']['coordinates'][0]) feature['geometry']['coordinates'] = [rect2poly(*coordinates)] geojson['features'] = features click.echo(json.dumps(geojson))
def maxrect(ctx, polygon, compare): """ Get an approximately maximal area, axis-aligned rectangle for a polygon represented by GeoJSON. """ if polygon == '-': src = click.open_file('-') if not src.isatty(): data = src.read() else: click.echo(ctx.get_usage()) ctx.exit(1) else: with open(polygon, 'r') as src: data = src.read() geojson = json.loads(data) if geojson.get('type') == 'Feature': geojson = {'type': 'FeatureCollection', 'features': [geojson]} features = geojson.get('features') n_features = len(features) if compare: features = features + copy.deepcopy(features) for feature in features[:n_features]: coordinates = get_maximal_rectangle( feature['geometry']['coordinates'][0]) feature['geometry']['coordinates'] = [rect2poly(*coordinates)] geojson['features'] = features click.echo(json.dumps(geojson))