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

Tips for Python beginners to use the Scikit-image example for themselves

Next, I will write the content for Python beginners to play with the example of Scikit-image with a slight modification.

Let's continue with Normalized Cut as an example.

sphx_glr_plot_ncut_001.png

Consider processing this example for different images. First of all, this example is shown as it is.

.py:plot_ncut.py


from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt


img = data.coffee()

labels1 = segmentation.slic(img, compactness=30, n_segments=400)
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')

plt.figure()
io.imshow(out1)
plt.figure()
io.imshow(out2)
io.show()

** Hint: Learn how to create a function. ** **

If you want to process this process for various input images, Think about what to input, what to do, and what to return. For the time being, let's make the part to be processed for the img image a function. Japanese translation of Python standard documentation 4.6. Defining functions

An example after functionalization

.py:plot_ncut_ex1.py


from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt

def plotNcut(img):
    labels1 = segmentation.slic(img, compactness=30, n_segments=400)
    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')
    
    plt.figure()
    io.imshow(out1)
    plt.figure()
    io.imshow(out2)
    io.show()

img = data.coffee()
plotNcut(img)

How about that? For functionalization def function name (argument): Indented code

If you write like, you can make it a function for the time being. The fact that indentation is part of control syntax can be confusing to a complete beginner in Python. You don't need to write a return return value unless you return a value. ,

** Hint: Use for name in glob.glob ("* .jpg "): to work with multiple files. ** **

Script after rewriting

.py:plot_ncut_ex2.py


from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt

def plotNcut(img):
    labels1 = segmentation.slic(img, compactness=30, n_segments=400)
    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')
    
    plt.figure(1)
    io.imshow(out1)
    plt.figure(2)
    io.imshow(out2)
    io.show()

import cv2
import glob
for name in glob.glob("*.png "):
    img = cv2.imread(name)
    plotNcut(img)
    cv2.waitKey(100)

The for statement is a control syntax for processing data such as lists one by one.

python


for name in names:
    print name

And so on. Please see the following library for details. Python standard library 4.2. For statement

Python standard library glob — Unix-like pathname pattern expansion

Since the function is defined with def plotNcut (img) :, the description in the for statement is simple. cv2.waitKey (100) gives a waiting time to make the display easier to read.

** Hint: Let's take out the frame of the video and process it **

768x576.avi is the video data included in the OpenCV distribution. Let's run Normalized Cut using this video. OpenCV-Python has cv2.VideoCapture (), which can extract the image of each frame from the video. (If you give the camera number as an argument, you can import the image from the USB camera.)

First, let's check if the video playback is made with an existing script. OpenCV-Tutorials Getting Started with Videos If you try this and the video doesn't play, it's likely that cap.isOpend () is False from the beginning. A common situation is that the python interpreter has not found a DLL such as opencv_ffmpeg2411.dll.

Note Make sure proper versions of ffmpeg or gstreamer is installed. Sometimes, it is a headache to work with Video Capture mostly due to wrong installation of ffmpeg/gstreamer.

There is, so please check the solution on the web. (If you use OpenCV 2.4.11, openCV 2.4.11 cv2.pyd in (Python directory) /Lib/site-packages/ Replace with. Also, copy opencv_ffmpeg2411.dll and paste it in the place where the script is, so that ffmpeg has a path. )

Script after rewriting

python


from skimage import data, io, segmentation, color
from skimage.future import graph
from matplotlib import pyplot as plt

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
while cap.isOpened():
    i += 1
    ret, img = cap.read()
    if i % 10 != 0:
        continue
    if ret != True:
        break
    [h, w] = img.shape[:2]
    img = cv2.resize(img, (w/2, h/2))
    out1, out2 = plotNcut(img)
    cv2.imshow("img", out1)
    cv2.waitKey(100)
    print i
        

Notice the part related to the variable cap set by cap = cv2.VideoCapture (name). The methods of isOpened () and read () are OpenCV-Python Tutorials Getting Started with Videos As it is written in the example of.

An example of input image and result image org_0000.pngimg_0000.png

Challenge: Using cv2.VideoCapture (), Edge operators Let's write a program that processes the example of.

sphx_glr_plot_edge_filter_001.png

development

In addition to glob.glob (file pattern), there is os.walk () as a way to find the file to process. You can search for files while moving directories in a hierarchical directory structure. (This is a feature I often use) os.walk(top, topdown=True, onerror=None, followlinks=False) Python standard library os — miscellaneous operating system interfaces

** Addendum: File list shuffle **

Another pattern for processing multiple files is to process from a file list. Depending on the process, it may be necessary to select the file with a random number. In the following example, shuffle the lines from the file list and select 100 lines from it. Can be processed.

python


lines = open("filelist.txt", "rt").readlines()
random.shuffle(lines)
for line in lines[:100]:
    p = line.strip()
    print p

Hint 3 Write to file


If you have Python 3.4 or later, you should throw away os.path and use pathlib

Recommended Posts

Tips for Python beginners to use the Scikit-image example for themselves 2 Handle multiple files
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 the Scikit-image example for themselves 8 Processing time measurement and profiler
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
~ Tips for beginners to Python ③ ~
The fastest way for beginners to master Python
[For beginners] How to use say command in python!
[python] How to use the library Matplotlib for drawing graphs
I didn't know how to use the [python] for statement
Beginners use Python for web scraping (1)
Beginners use Python for web scraping (4) ―― 1
[Introduction to Python] How to use the in operator in a for statement?
I tried to refer to the fun rock-paper-scissors poi for beginners with Python
[Example of Python improvement] What is the recommended learning site for Python beginners?
[Python] Organizing how to use for statements
How to use "deque" for Python data
Tips for those who are wondering how to use is and == in Python
How to use the C library in Python
How to use MkDocs for the first time
Python for super beginners Python for super beginners # Easy to get angry
Specify the Python executable to use with virtualenv
Memo # 3 for Python beginners to read "Detailed Python Grammar"
Use logger with Python for the time being
Memo # 1 for Python beginners to read "Detailed Python Grammar"
How to use data analysis tools for beginners
Tips for hitting the ATND API in Python
Use cryptography module to handle OpenSSL in Python
The easiest way to use OpenCV with python
Try to calculate RPN in Python (for beginners)
[Algorithm x Python] How to use the list
Use the Python framework "cocotb" to test Verilog.
Memo # 2 for Python beginners to read "Detailed Python Grammar"
How to get the files in the [Python] folder
Memo # 7 for Python beginners to read "Detailed Python Grammar"
Introduction to Programming (Python) TA Tendency for beginners
Memo # 6 for Python beginners to read "Detailed Python Grammar"
How to make Python faster for beginners [numpy]
~ Tips for Python beginners from Pythonista with love ② ~
[For beginners] Web scraping with Python "Access the URL in the page to get the contents"
python beginners tried to predict the number of criminals
[BigQuery] How to use BigQuery API for Python -Table creation-
Beginners can use Python for web scraping (1) Improved version
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
How to use the Raspberry Pi relay module Python
[Python] Local → Procedure for uploading files to S3 (boto3)
I wanted to use the Python library from MATLAB
[Python] How to use the graph creation library Altair
[Introduction for beginners] Reading and writing Python CSV files
[Python] How to split and modularize files (simple, example)
Specify MinGW as the compiler to use with Python
[Introduction to Udemy Python3 + Application] 27. How to use the dictionary
[Introduction to Udemy Python3 + Application] 30. How to use the set
How to use the model learned in Lobe in Python
Python # How to check type and type for super beginners
I want to use the R dataset in python
Beginners use Python for web scraping (4) --2 Scraping on Cloud Shell