I will explain how to crop an image using OpenCV. This is a continuation of Last time, so if you have any questions in this article, please have a look.
MacOS Mojave Python 3.7
Use the image below (neko.jpg).
You can check the size of the image with the following code.
python
#Loading the library
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("neko.jpg ")
print(img.shape)
When I run the above code, I get the following results:
(900, 1600, 3)
This means 900 pixels vertically, 1600 pixels horizontally, and 3 channels. In the case of a color image, the number of channels is 3 because it is GBR. In grayscale, the number of channels is 1 because it is only the degree of whiteness.
In Opencv, the coordinate axes of the image are as follows.
When the position is (x, y), the origin (0,0) is at the upper left as shown in the figure. When dealing with images, please note that the downward direction is the positive direction of the y-axis. The size of this image is 900 pixels vertically and 1600 pixels horizontally, so the x and y coordinates of the pixels at the end of the image are 899 and 1599, respectively. The reason why it does not become 900 or 1600 is that it counts from the origin 0.
If you specify the coordinates of the image as follows, you can get the color value of that position.
python
img = cv2.imread("neko.jpg ")
print(img[450,800])
output
[153 161 190]
This indicates that the color at the coordinate (450,800) position is (R, G, B) = (153,161,190). Also, you can specify multiple coordinates by doing the following.
print(img[450:650,800:1000])
[[[153 161 190]
[153 161 190]
[152 160 189]
...
[169 178 205]
[169 178 205]
[169 178 205]]
[[152 160 189]
[152 160 189]
[153 161 190]
...
[169 178 205]
[169 178 205]
[169 178 205]]
[[151 159 188]
[152 160 189]
[154 162 191]
...
[171 178 205]
[172 179 206]
[172 179 206]]
...
Omitted below. .. ..
Think of the ":" in [] as the same as the "~" we usually use to represent a range of numbers. In the above example, the color information in the range from coordinates (450,800) to (649,999) is output.
If you put the specified range of the image in another object, you can get the image with the position cut out.
python
#Loading the library
import cv2
import matplotlib.pyplot as plt
img = cv2.imread("neko.jpg ")
#Img the specified pixel_Substitute for trim
img_trim = img[450:650,800:1000]
#Change color
img_trim = cv2.cvtColor(img_trim, cv2.COLOR_BGR2RGB)
#display
plt.imshow(img_trim)
plt.show()
If the above image is output, it is successful! (Since it is a tatami mat, it is difficult to tell if it is cut out ... lol) Next time, I'd like to explain the work of kneading, such as scaling and flipping images: blush:
If you would like to do various things such as information on future articles and questions and answers, please follow me ...! : relieved: https://twitter.com/ryuji33722052
Recommended Posts