Tips for Python beginners to use Scikit-image examples for themselves 3 Write to a file

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

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

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

Continue to Normalized Cut

sphx_glr_plot_ncut_001.png

Will be on the agenda.

In [Tips 2 for Python beginners to use the Scikit-image example for themselves, processing multiple files], I was able to process various images.

However, you may be dissatisfied because the result cannot be saved in the file as it is.

So I would like to give you some tips for saving to a file.

** OpenCV-Save image with Python **

cv2.imwrite("out.png ", img) OpenCV-Python Tutorials >> Getting Started with Images

** Save image as serial number file **

python


for  i in range(len(names)):
    img = cv2.imread(names[i])
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    oname = "gray_%04d.png "  % i
    cv2.imwrite(oname, gray)

The function equivalent to the formatting of prinft () / sprinft () / fprintf () in C language is Python standard library / string format operation It is in.

** Operations related to directories and file names **

os.path.dirname() os.path.basename() os.path.splitext() os.path.join()

Python standard library / os.path — common path name operation

If the output directory odir does not exist, It is customary to create a directory as follows:

python


if not os.path.isdir(odir):
    os.makedirs(odir)

Python standard library / os — miscellaneous operating system interfaces

os.makedirs (path [, mode]) Recursive directory creation function. Similar to mkdir (), but creates all the intermediate directories needed to create the leaf directory.

oname = os.path.join(odir, "img_%05d.png " % i) If you include the output directory in the output file name like You can output to a directory other than the script execution directory.

** Operations related to string replacement **

The output file name can also be generated from the input file name by the replace function. The string has a replace () method, which returns the replaced string as a return value. replace(old, new[, count]) Python standard library / string methods

Using these functions, you can freely set the file name of the output destination.

Task:

"Hint: Let's process multiple files using for name in glob.glob (" * .jpg "):" Let's try to save the result to a file based on the example shown in. Condition: Create an output directory "out" and save the file there. Condition: For the input "image.jpg ", save it with the file name "out / image_ncut.png ".

You should be able to code with the hints given so far. Enjoy the OpenCV-Python, scikit-image, scikit-learn libraries even if you are new to Python.

** Note: **

-When writing directory delimiters in Python, you can use the "/" character like "abc / def.txt" even on Windows. -If you want to use the delimiter with "", it is convenient to add the symbol r before "" like name = r "abc \ def.txt". In that case, you don't have to write name = "abc \\ def.txt" (two "" characters are written).

In Python 3

https://docs.python.jp/3/library/pathlib.html Seems to be better to use.

python


# -*- coding: utf-8 -*-
# pylint: disable=C0103
import pathlib
from skimage import io, segmentation, color
from skimage.future import graph

def plotNcut(img):
    """
    img: color img

    """

    labels1 = segmentation.slic(img, compactness=30, n_segments=400)
    g = graph.rag_mean_color(img, labels1, mode='similarity')
    labels2 = graph.cut_normalized(labels1, g)
    return color.label2rgb(labels2, img, kind='avg'), labels2

if __name__ == "__main__":
    oDir = pathlib.Path("out")
    if not oDir.is_dir():
       oDir.mkdir() 
    for p in pathlib.Path("../images").glob("*.png "):
        print(p)
        
        oname = oDir.joinpath(p.with_suffix(".jpg ").name)
        img = io.imread(p)
        out, _ = plotNcut(img)
        io.imsave(str(oname), out)
        print(oname)

Hint 4 Use GUI

Recommended Posts

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 4 Use GUI
Tips for Python beginners to use the Scikit-image example for themselves
Tips for Python beginners to use Scikit-image examples for themselves 5 Incorporate into network apps
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 9 Use from C
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 2 Handle multiple files
Tips for Python beginners to use the Scikit-image example for themselves 8 Processing time measurement and profiler
~ Tips for beginners to Python ③ ~
I want to write to a file with Python
Use a scripting language for a comfortable C ++ life-OpenCV-Port Python to C ++-
How to write a Python class
[Python] Write to csv file with Python
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?
[For beginners] How to register a library created in Python in PyPI
[Python] Organizing how to use for statements
How to use "deque" for Python data
A textbook for beginners made by Python beginners
I made a Docker container to use JUMAN ++, KNP, python (for pyKNP).
[Python] It was very convenient to use a Python class for a ROS program.
Error due to UnicodeDecodeError when reading CSV file with Python [For beginners]
Memo # 4 for Python beginners to read "Detailed Python Grammar"
How to read a CSV file with Python 2/3
The fastest way for beginners to master Python
Python for super beginners Python for super beginners # Easy to get angry
Tips for those who are wondering how to use is and == in Python
How to create a JSON file in Python
[Python] Concatenate a List containing numbers and write it to an output file.
Memo # 1 for Python beginners to read "Detailed Python Grammar"
~ Tips for Python beginners from Pythonista with love ① ~
How to use data analysis tools for beginners
How to write a ShellScript Bash for statement
Export Python3 version OpenCV KeyPoint to a file
Python script to get a list of input examples for the AtCoder contest
Searching for an efficient way to write a Dockerfile in Python with poetry
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 ② ~
Memo # 5 for Python beginners to read "Detailed Python Grammar"
How to use pip, a package management system that is indispensable for using Python
[Python] I want to use only index when looping a list with a for statement
A python script that wants to use Mac startup / end time for attendance management
How to use NUITKA-Utilities hinted-compilation to easily create an executable file from a Python script
Create a dataset of images to use for learning
[BigQuery] How to use BigQuery API for Python -Table creation-
Beginners can use Python for web scraping (1) Improved version
Parse a JSON string written to a file in Python
Write about building a Python environment for writing Qiita Qiita
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
I want to write in Python! (2) Let's write a test
How to write a list / dictionary type of Python3
A memorandum to run a python script in a bat file
[Introduction to python] A high-speed introduction to Python for busy C ++ programmers
I want to randomly sample a file in Python
[Python] How to write a docstring that conforms to PEP8