Recently, Python has become a hot topic. In Python, you can perform simple image processing by using a library called OpenCV. In this article, I will explain how to read an image with OpenCV and process it in various ways.
MacOS Mojave Python 3.7.6
Install libraries called opencv and matplotlib. matplotlib is a library for drawing graphs and can also be used for displaying images. Type the following commands into the terminal and execute them.
$pip install opencv-python
$pip install matplotlib
Please note that you cannot install with "opencv" alone. If Requirement already satisfied is displayed and you enter, there is no problem because it is already installed.
This time, I will use the image of the following cat (neko.jpg).
Execute the following code.
opencv_read_img.py
#Loading the library
import cv2
import matplotlib.pyplot as plt
#neko.Load a jpg and put it in an img object
img = cv2.imread("neko.jpg ")
#Display img object using matlotlib
plt.imshow(img)
plt.show()
The first import part loads opencv (cv2) and matplotlib's pyplot (matplotlib.pyplot). As plt means that matplotlib.pylot is long, so I will abbreviate it to plt and use it from now on.
If you execute the above code and the following screen appears, it is successful.
However, the cat has a strange color, right? This is due to the different color representations of GBR (green / blue / red) in opencv and RGB (red / green / blue) in matplotlib. Therefore, in order to express with the original color, it is necessary to convert the color.
After loading the image, use cv2.cvtColor ().
opencv_read_img.py
#Loading the library
import cv2
import matplotlib.pyplot as plt
#neko.Load a jpg and put it in an img object
img = cv2.imread("neko.jpg ")
#Convert image color order from BGR to RGB
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
#Display img object using matlotlib
plt.imshow(img)
plt.show()
When the above code is executed, the following screen will be output. The original image is displayed! Next time, I will explain how to perform simple image processing and save it.
python: can't open file 'opencv_read_img.py': [Errno 2] No such file or directory
This is an error that the file does not exist. In this case, follow the procedure below.
① Place the image in the same location as the created python file.
② Move to the folder where the python file is placed in the terminal. If you have python files and images in a folder called qiita_python on your desktop, run the following command.
$cd /Users/username/Desktop/qiita_python
$python opencv_read_img.py
Please follow me if you like! https://twitter.com/ryuji33722052
Recommended Posts