Skip to content

Instantly share code, notes, and snippets.

@keimina
Created March 15, 2016 22:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save keimina/3cf01e8991e0cdc86aea to your computer and use it in GitHub Desktop.
Save keimina/3cf01e8991e0cdc86aea to your computer and use it in GitHub Desktop.
from subprocess import call
from pylab import *
from mpl_toolkits.axes_grid1 import make_axes_locatable
from matplotlib.patches import Rectangle
from time import sleep
import cv2
# Read template image
templateImageGray = cv2.imread("./images/templateImage.png", cv2.IMREAD_GRAYSCALE)
templateImageGray = cv2.resize(templateImageGray, (0, 0), fx=16, fy=16, interpolation=cv2.INTER_CUBIC)
# Convert template image to binary image
_, templateImageBlackWhite = cv2.threshold(templateImageGray, 127, 255, cv2.THRESH_BINARY)
# Convert binary image to labeled image
numOfLabelOfTemplateImage, templateImageLabeled, stats, centroids = cv2.connectedComponentsWithStats(templateImageBlackWhite, connectivity=8)
## Draw rectangle to labeled image
pt1Stats = stats[:, 0:2]
pt2Stats = pt1Stats + stats[:, 2:4]
templateImageLabeledWithRect = np.array(templateImageLabeled)
for pt1, pt2 in zip(pt1Stats, pt2Stats):
pt1 = tuple(pt1)
pt2 = tuple(pt2)
cv2.rectangle(templateImageLabeledWithRect, pt1, pt2, (255, 255, 0), thickness=10)
## Put text to labeled image
#cv2.putText(
print "Number of labeled objects is %d" % numOfLabelOfTemplateImage
################ Plot ################
ax = plt.subplot(411)
plt.title("templateImageGray")
plt.imshow(templateImageGray, cmap="gray", interpolation="nearest")
ax = plt.subplot(412)
plt.title("templateImageBlackWhite")
plt.imshow(templateImageBlackWhite, cmap="gray", interpolation="nearest")
ax = plt.subplot(413)
plt.title("templateImageLabeled")
plt.imshow(templateImageLabeled, interpolation="nearest")
ax = plt.subplot(414)
plt.title("templateImageLabeledWithRect")
plt.imshow(templateImageLabeled, interpolation="nearest")
# Draw rectangle to labeled image
xys = stats[:, 0:2]
whs = stats[:, 2:4]
for n, (xy, wh) in enumerate(zip(xys, whs)):
ax.text(xy[0], xy[1], str(n), verticalalignment="bottom")
ax.add_patch(Rectangle(xy, *wh, fill=None, color="#ff0000", linewidth=1))
plt.tight_layout()
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment