Tips for Python beginners to use the Scikit-image example for themselves 8 Processing time measurement and profiler

Scikit-image, scikit-learn, Processing time when using OpenCV-Python concern. So, in this article, I'll show you the gateway to measuring processing time and profiling.

** Measurement of processing time **

import cv2 The OpenCV binding is already available in an error-free environment. Cv2.getTickCount (), cv2.getTickFrequency () in it You can use to measure the processing time. An example of an article Measuring performance with OpenCV This function works the same on both Windows and Linux, so you can measure processing time without compromising script portability.

Based on the examples that have been used repeatedly so far, let's measure how the processing time changes when the input image size is changed. [Normalized Cut] (http://scikit-image.org/docs/dev/auto_examples/segmentation/plot_ncut.html#example-segmentation-plot-ncut-py) Normalized Cut Let's change the size of the input image with the example of.

** Example: Change in execution time depending on image size **

.py:ex_getTickCount.py


from skimage import data, segmentation, color
from matplotlib import pyplot as plt
import cv2

img0 = data.coffee()

x=[]
y=[]

a=1.2
for i in range(10):
    r=a**i
    newSize=(int(img0.shape[1]/r), int(img0.shape[0]/r))
    img=cv2.resize(img0, newSize)
    t1=cv2.getTickCount()
    labels1 = segmentation.slic(img, compactness=30, n_segments=400)
    out1 = color.label2rgb(labels1, img, kind='avg')
    t2=cv2.getTickCount()
    dt=(t2-t1)/cv2.getTickFrequency()
    print newSize, dt
    x.append(newSize[0])
    y.append(dt)
    
plt.figure(1)
plt.plot(x,y, "*-")
plt.xlabel("width")
plt.ylabel("time [sec]")
plt.grid(True)
plt.show()

ex_getTickCount.png

Figure: Change in execution time depending on image size

If you look at the graph, you can see that when the width of the image is doubled, the processing time is quadrupled. In other words, if the width of the image is halved, the processing time will be 1/4 times longer. To make this the same processing time while keeping the width of the image the same is equivalent to reducing the processing time by 75%. In general, such speeding up is not easy, and in the case of processing in which the image may be reduced, reducing the size of the image is a standard for shortening the processing time.

** Example: Change in execution time at each frame of video (time series and histogram) **

First, Tips for Python beginners to use the Scikit-image example for themselves 2 Process multiple files Introduced a script that processes Normalized Cut for each frame. This time, based on that, I measured the processing time in each frame and made a graph of the result.

.py:ex_plot_ncut2_time.py


from skimage import data, io, segmentation, color
from skimage.future import graph
import cv2

def plotNcut(img):    
    labels1 = segmentation.slic(img, compactness=30, n_segments=200)
    out1 = color.label2rgb(labels1, img, kind='avg')
    
    g = graph.rag_mean_color(img, labels1, mode='similarity')
    labels2 = graph.cut_normalized(labels1, g)
    out2 = color.label2rgb(labels2, img, kind='avg')

    return out1, out2

name="768x576.avi"
cap=cv2.VideoCapture(name)
i= -1
out=open("time_data.txt", "wt")
while cap.isOpened():
    i += 1
    ret, img=cap.read()
    if ret != True:
        break
    if i>100:
        break
    [h, w] = img.shape[:2]
    img = cv2.resize(img, (w/2, h/2))
    t1=cv2.getTickCount()
    out1, out2 = plotNcut(img)
    t2=cv2.getTickCount()
    dt=(t2-t1)/cv2.getTickFrequency()
    out.write("%f\n" % dt)
    cv2.imshow("img", out1)
    cv2.waitKey(100)
    cv2.imwrite("org_%04d.png " % i,  img)
    cv2.imwrite("img_%04d.png " % i,  out1)
    print i
    
out.close()

.py:view_data.py


import numpy as np
import pylab

name="time_data.txt"

data=np.loadtxt(name)

print data

pylab.figure(1)
pylab.subplot(1,2,1)
pylab.plot(data)
pylab.ylabel("time[s]")
pylab.grid(True)
pylab.subplot(1,2,2)
pylab.hist(data)
pylab.grid(True)
pylab.xlim([3, 4])
pylab.xlabel("time[s]")
pylab.show()

figure_1.png

By displaying the time series or the histogram in this way, it becomes easier to evaluate how much the processing time can change depending on the scene, rather than measuring the processing time only once. Trying to use it is one of the clues to understand the method.

** Using Profiler **

Python has a profiler in the standard library, so you can profile python scripts regardless of OS or CPU type such as Windows or Linux. In the case of C ++, the profiling method differs depending on the OS, compiler type, and tool type. Even if the tools have the same name, the usage may be extremely different depending on the version, and you may feel inconvenienced. In that respect, the Python profiler is Python standard library 26.4. Python profiler You can run the profiler in a simple way, as shown in.

The main entry point for profilers is the global function profile.run () (or cProfile.run ()).

Blog article Python code profiling

Please try to imitate how to use it by looking at examples such as.

What is the largest breakdown of processing time in profile.run ()? Is the number of function calls as expected, or is the function called more than expected? I check those parts.

You can compare the operating time and breakdown of the same python script with the same profiler between the source Python (for example, Windows) and the destination python.

The processing time of OpenCV-Python functions (for example, face detection and person detection) varies significantly depending on how the OpenCV cv2.pyd used is built and whether the CPU is multi-core. That should become apparent when you test it with a Python profiler.

Task:

Tips for Python beginners to use the Scikit-image example for themselves 2 Process multiple files

Based on the example of processing multiple files and processing in multiple frames in Let's measure the execution time.

matplotlib has a hist () function that makes it easy to create histograms. Let's actually measure how much the processing time varies and create a histogram.

** Reference article **

Why detectMultiScale () is slow on Raspberry Pi

Let's check parallel_for

** Reference books **

Micha Gorelick, Ian Ozsvald, translated by Aizo Aikawa, "High Performance Python"

About the processing speed of SVM (SVC) of scikit-learn Is an example of a practical article about time measurement.

Note: When I realized that it would be okay to replace the part that took too much time in image processing with a reduced image, I tried reducing the image size. The processing time has been dramatically reduced. Python has a simple profile, so you can quickly identify which process is taking a long time. Once that is identified, only speed up that part. Of the many lines, just adding the process of reducing the image to one of them can increase the processing speed by 10 times or more.

Hint 9 Use from C language

Recommended Posts

Tips for Python beginners to use the Scikit-image example for themselves 8 Processing time measurement and profiler
Tips for Python beginners to use the Scikit-image example for themselves
Tips for Python beginners to use the Scikit-image example for themselves 6 Improve Python code
Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module
Tips for Python beginners to use Scikit-image examples for themselves 4 Use GUI
Tips for Python beginners to use Scikit-image examples for themselves 3 Write to a file
Tips for Python beginners to use Scikit-image examples for themselves 5 Incorporate into network apps
[Python] Measures and displays the time required for processing
~ Tips for beginners to Python ③ ~
The fastest way for beginners to master Python
How to use MkDocs for the first time
Use logger with Python for the time being
Tips for those who are wondering how to use is and == in Python
[For beginners] How to use say command in python!
Python # How to check type and type for super beginners
Lists, functions, for, while, with (open), class and learning supplements up to the last time (Python beginners after learning Ruby)
[python] How to use the library Matplotlib for drawing graphs
How to learn TensorFlow for liberal arts and Python beginners
I didn't know how to use the [python] for statement
Python environment construction and SQL execution example to DB and memo of basic processing for statistics 2019
I tried to create serverless batch processing for the first time with DynamoDB and Step Functions
The story of returning to the front line for the first time in 5 years and refactoring Python Django
Determine the date and time format in Python and convert to Unixtime
processing to use notMNIST data in Python (and tried to classify it)
[Introduction to Python] How to use the in operator in a for statement?
[Introduction to Python] How to use the Boolean operator (and ・ or ・ not)
Leave the troublesome processing to Python
See python for the first time
Beginners use Python for web scraping (1)
Beginners use Python for web scraping (4) ―― 1
python> Processing time measurement> time.time () --start_time
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
Beginners use Python for web scraping (4) -3 GCE VM instance creation and scraping on VM
I want to separate the processing between test time and production environment
[Python] [Machine learning] Beginners without any knowledge try machine learning for the time being
How to get the date and time difference in seconds with python
Try to make foldl and foldr with Python: lambda. Also time measurement
[Example of Python improvement] What is the recommended learning site for Python beginners?
[Python] How to use the enumerate function (extract the index number and element)
Technique to stop drawing the screen and reduce the waiting time for baking
How to install and use pandas_datareader [Python]
Create a command to search for similar compounds from the target database with RDKit and check the processing time
Python Master RTA for the time being
[Python] Organizing how to use for statements
MongoDB for the first time in Python
python: How to use locals () and globals ()
How to use "deque" for Python data
How to use Python zip and enumerate
How to use is and == in Python
OpenGoddard How to use 2-python library for nonlinear optimal control and orbit generation
How to use OpenGoddard 3-python library for nonlinear optimal control and orbit generation
Use libsixel to output Sixel in Python and output a Matplotlib graph to the terminal.
How to use OpenGoddard 4-python library for nonlinear optimal control and orbit generation
How to use Service Account OAuth and API with Google API Client for python
How to use OpenGoddard 1-python library for nonlinear optimal control and orbit generation
How to use the C library in Python
Use the retry processing mode added to Boto3
Python for super beginners Python for super beginners # Easy to get angry
Causal reasoning and causal search with Python (for beginners)
Specify the Python executable to use with virtualenv
Memo # 3 for Python beginners to read "Detailed Python Grammar"