Identify complex polygons using BoofCV approach
Source code name: "identify_polygon_binary.py"
Programming language: Python
Topic: Images/Shape identification
DMelt Version 1.7. Last modified: 07/30/1970. License: Pro
https://datamelt.org/code/cache/identify_polygon_binary_6419.py
To run this script using the DMelt IDE, copy the above URL link to the menu [File]→[Read script from URL] of the DMelt IDE.


# shows how to identify / recognize polygons using images.
# It uses binary approach for contour identification

from  boofcv.alg.feature.detect.edge import CannyEdge,EdgeContour,EdgeSegment
from boofcv.alg.filter.binary import BinaryImageOps,Contour,ThresholdImageOps
from boofcv.alg.misc import ImageStatistics
from boofcv.alg.shapes import ShapeFittingOps
from boofcv.factory.feature.detect.edge import FactoryEdgeDetectors
from boofcv.gui import ListDisplayPanel
from boofcv.gui.feature import VisualizeShapes
from boofcv.gui.image import ShowImages
from boofcv.io import UtilIO
from boofcv.io.image import UtilImageIO,ConvertBufferedImage
from boofcv.struct import ConnectRule,PointIndex_I32
from boofcv.struct.image import GrayF32,GrayU8
from georegression.struct.point import Point2D_I32
from java.awt import *
from java.awt.image import BufferedImage
from java.util import List
from java.util import Random

# get image
from jhplot import *
http="http://datamelt.org/examples/data/"
print Web.get(http+"polygons.png")


image = UtilImageIO.loadImage("polygons.png")
input = ConvertBufferedImage.convertFromSingle(image, None, GrayF32)
splitFraction = 0.05
minimumSideFraction = 0.1
gui=ListDisplayPanel()
gui.addImage(image,"Original")


binary = GrayU8(input.width,input.height)
polygon =  BufferedImage(input.width,input.height,BufferedImage.TYPE_INT_RGB)

# the mean pixel value is often a reasonable threshold when creating a binary image
mean = ImageStatistics.mean(input)

# create a binary image by thresholding
ThresholdImageOps.threshold(input, binary, mean, True)

filtered = BinaryImageOps.erode8(binary, 1, None)
filtered = BinaryImageOps.dilate8(filtered, 1, None)

contours = BinaryImageOps.contour(filtered, ConnectRule.EIGHT,None)
g2 = polygon.createGraphics()
g2.setStroke(BasicStroke(2))

for c in contours:
   vertexes = ShapeFittingOps.fitPolygon(c.external,True,
					splitFraction, minimumSideFraction,100)
   g2.setColor(Color.RED)
   VisualizeShapes.drawPolygon(vertexes,True,g2)
   g2.setColor(Color.BLUE)
   for internal in c.internal: 
      vertexes = ShapeFittingOps.fitPolygon(internal,True, splitFraction, minimumSideFraction,100)
      VisualizeShapes.drawPolygon(vertexes,True,g2)

gui.addImage(polygon, "Binary Blob Contours")
ShowImages.showWindow(gui, "Polygon from Contour", True)


You see the box below because you did not login.