Skip to content

Instantly share code, notes, and snippets.

@odeke-em
Created May 5, 2018 07:39
Show Gist options
  • Save odeke-em/c66b35dd4ed6dfc7c807f2585dc15cc1 to your computer and use it in GitHub Desktop.
Save odeke-em/c66b35dd4ed6dfc7c807f2585dc15cc1 to your computer and use it in GitHub Desktop.
Tracing an OpenCV tutorial app with OpenCensus Python
#!/usr/bin/env python3
"""
Copyright 2018, OpenCensus Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
u may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
import os
# OpenCV stuff
import cv2
import numpy as np
from matplotlib import pyplot as plt
# Tracing
from opencensus.trace.samplers import always_on
from opencensus.trace.exporters import stackdriver_exporter
from opencensus.trace.exporters.transports.background_thread import BackgroundThreadTransport
from opencensus.trace.tracer import Tracer
def createAveraged(tracer, img):
with tracer.span(name='createAveraged') as span:
span.add_annotation('Creating Kernel')
kernel = np.ones((5, 5), np.float32)/25
span.add_annotation('Finished creating Kernel')
span.add_annotation('Creating averaged image')
dst = cv2.filter2D(img, -1, kernel)
span.add_annotation('Finished creating averaged image')
return dst
def drawBeforeAndAfterImages(tracer, plt, before, after):
with tracer.span(name='drawBeforeAndAfterImages') as span:
span.add_annotation('Starting to write original image')
plt.subplot(121)
plt.imshow(before)
plt.title('Original')
plt.xticks([])
plt.yticks([])
span.add_annotation('Finished writing original image')
span.add_annotation('Starting to write averaged image')
plt.subplot(122)
plt.imshow(after)
plt.title('Averaging')
plt.xticks([])
plt.yticks([])
span.add_annotation('Finished writing averaged image')
def retrieveImage(tracer, path):
with tracer.span(name='imread') as span:
span.add_annotation('Starting imread')
img = cv2.imread(path)
span.add_annotation('Finished imread')
return img
def main():
# Create the tracer
exporter = stackdriver_exporter.StackdriverExporter(
project_id=os.environ.get('TRACED_CV_PROJECTID', 'census-demos'),
transport=BackgroundThreadTransport)
tracer = Tracer(sampler=always_on.AlwaysOnSampler(), exporter=exporter)
with tracer.span(name='Visualize image'):
img = retrieveImage(tracer, 'opencensus-logo.png')
dst = createAveraged(tracer, img)
drawBeforeAndAfterImages(tracer, plt, img, dst)
plt.show()
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment