Tips for Python beginners to use the Scikit-image example for themselves 7 How to make a module

I will continue to write content for Python beginners.

One of the reasons why Python has expanded its use is the existence of its extensive library. The reason why using the GUI and writing network apps is so easy is clearly that the Python library is extensive.

This time, I will explain how to write Python to improve reusability so that the script already written can be used as a module.

** Language with few promises **

Python is a language with very few promises to start writing programs.

print "Hello World"

It is a good Python program even if you just write. In the case of C / C ++ language, you need to write the main function. In the case of Java, you need to create a class and define a method called public static void main (String [] args). Such promises are inevitable in learning the language. You can start using the Python language with few such promises.

a = 1
b = 2
print a+b

The fact that it can be described as is due to the small number of promises.

** All objects can be printed **

From the python language, the promise to the user is Most objects print The object's identifier It means that you can print with.

The point is that you can print numbers, strings, lists, tuples, dictionaries, numpy.array types, class instances, and objects handled by the python language.

This does not force Python users to use C language printf ("% d", int type variable), printf ("% f", double type variable), etc., and there is room for incorrect usage. I'm missing it. Being able to print no matter how complex the data format is makes it possible to understand by printing even if the return value of a function that you do not know how to use is in any complex data format.

Note: On the Python interpreter

>>> a+b
3
>>> 

Just do, it will display the object without print.

Note: print is a special print statement, not a function. There is also a print () function, which can be used in the same way. Therefore, in the python source code you see, the Python 2.x series tends to use the print statement, and the Python 3.x series tends to use the print () function.

** Promises for Python users **

The Python language uses indentation as a range of control syntax for if statements, while statements, for statements, and so on. For this reason, the copy-and-paste script will behave differently if the indentation is different from the original script.

Until I get used to it, it seems that it is a dragonfly that is cut off, and I may be confused as to "Where did the rest go?", But as I get a useful example of the Python language, I naturally get used to it. I think you can.

** Let's import **

In the Python language, if you use the import module name, you can access the functions in the module with the module name.function name.

import cv2 img = cv2.imread("lena.jpg ") Can be done.

Written by myself myModule.py Function in myfunc () When there is import myModule myModule.myfunc() You can use your own library at.

.py:modNcut.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()

After creating the function In the directory where this function is (or if this module has PYTHONPATH)

import modNcut
import cv2
img = cv2.irmread("lena.jpg ")
modNcut.plotNcut(img)

Can be used as. The fact that you can use your own modules without compiling, registering, or any special work makes it very easy to proceed with development. What kind of specifications should the function be made, especially how to make its arguments and return values easy to use? It will be very easy to actually write it and check it while using it.

The lack of conventions in the python language is also reflected in how to write modules to install.

** Almost the only convention when writing a module **

-Write the code that you do not want to execute when you call it as a module (= the code that you want to execute only when you select it as the main program) in the if statement of ```if name == "main": `` `.

In the Python language, the part corresponding to the main function of the C / C ++ language is described in the following if statement part. if __name__ == "__main__": The range of if statements that start with `` `is the part that will only be executed when the script file is executed as main. When the script file is called by the import statement, the range of the if statement starting with if name == "main": `` `is not executed.

python



 [__main__ — Top-level scripting environment](http://docs.python.jp/2/library/__main__.html)

 Python Tutorial [Modules](http://docs.python.jp/2.7/tutorial/modules.html)


### ** Implementation of Python module **
 There are actually various implementations of modules in the python language. A module written in the python language. A module written in C / C ++. A module written based on the Cython language. Everything
 import module name
 You can import with. Everything is common, such as getting a description of a function with help (module name.function name).
 If you have Python (x, y) installed,
 From the start menu
[Python(x,y)][Documentation]
 "Python: Index of Modules" in [open browser] in [python documentation server]
 You can set up your web server locally.
 All python modules are common, such as being able to find function and class descriptions by tracing the libraries available on that browser screen.


 Postscript
 Reference URL
 [PyCon JP 2012 Python Programming Hands-on (Beginner) documentation Script Files and Modularization](http://pyconjp2012-python-for-beginners.readthedocs.org/en/latest/script_module.html)
 [1.2.5. Code Reuse: Scripts and Modules](http://www.turbare.net/transl/scipy-lecture-notes/intro/language/reusing_code.html)




 [Hint 8 Processing time measurement and profiler](http://qiita.com/nonbiri15/items/fa9036f612183fb3d242)


Recommended Posts

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
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 Scikit-image examples for themselves 3 Write to a file
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 5 Incorporate into network apps
[Introduction to Python] How to use the in operator in a for statement?
How to make Python faster for beginners [numpy]
[Python] Explains how to use the range function with a concrete example
~ Tips for beginners to Python ③ ~
[For beginners] How to use say command in python!
How to use the Raspberry Pi relay module Python
How to use the optparse module
[python] How to use the library Matplotlib for drawing graphs
How to use the __call__ method in a Python class
How to make a Python package (written for an intern)
I didn't know how to use the [python] for statement
How to use the ConfigParser module
[For beginners] How to register a library created in Python in PyPI
[Python] Explains how to use the format function with an example
[Python] How to make a class iterable
[Python] Organizing how to use for statements
How to use "deque" for Python data
[Python] How to use the for statement. A method of extracting by specifying a range or conditions.
How to make a dialogue system dedicated to beginners
How to use the C library in Python
The fastest way for beginners to master Python
A simple example of how to use ArgumentParser
How to use MkDocs for the first time
How to make Spigot plugin (for Java beginners)
How to use data analysis tools for beginners
How to add a Python module search path
[Algorithm x Python] How to use the list
Let's make a module for Python using SWIG
Tips for those who are wondering how to use is and == in Python
[Introduction to Python] How to get the index of data with a for statement
[BigQuery] How to use BigQuery API for Python -Table creation-
Try to make a Python module in C language
How to convert Python # type for Python super beginners: str
[For beginners] How to study Python3 data analysis exam
[Python] How to use the graph creation library Altair
How to make a Python package using VS Code
[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
How to use pip, a package management system that is indispensable for using Python
python3: How to use bottle (2)
How to use the generator
[Python] How to use list 1
How to use Python argparse
Python: How to use pydub
[Python] How to use checkio
[Python] How to use input ()
How to use the decorator
How to use Python lambda
[Python] How to use virtualenv
python3: How to use bottle (3)