This article is a thin article written by a rare technical college student (transfer student) who has never even touched a PC, let alone python. There are quite a lot of points that I refer to the articles of other people. I hope you can see it with warm eyes.
This time, I will upload and process any image so that it is easy to use. You can upload it by using files.upload ()
.
When you execute the command, the upload form will be displayed, so please upload it.
After that, get the file name.
Upload
from google.colab import files
uploaded_file = files.upload()
img = next(iter(uploaded_file))
The image is read using OpenCV, but since the color of the image in OpenCV is handled by BGR instead of RGB, it is converted to general RGB. Then use matplotlib
to display the image.
Image display
import cv2
from matplotlib import pyplot as plt
img2 = cv2.imread(img)
#RGB conversion
src = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
#Image display
plt.imshow(src)
#Hide value
plt.axis('off')
This will display the original image.
Inverting colors is easy, just put src = 255 --src
. This takes advantage of the fact that the value is inverted by subtracting the original color value from white (255).
Color inversion
import cv2
from matplotlib import pyplot as plt
img2 = cv2.imread(img)
src = cv2.cvtColor(img2,cv2.COLOR_BGR2RGB)
#Inversion
src = 255 - src
plt.imshow(src)
plt.axis('off')
Execution result
Conversion to grayscale can be done with cv2.cvtColor (pixels, cv2.COLOR_BGR2GR)
.
That's the only difference from the original.
grayscale
import numpy as np
pixels = np.array(src)
import matplotlib.pyplot as plt
#Convert to grayscale
img_gray = cv2.cvtColor(pixels, cv2.COLOR_BGR2GRAY)
plt.imshow(img_gray)
plt.axis('off')
Execution result
Finally, it is binarization. Binarization is done by first converting to grayscale and then binarizing with cv2.threshold (img_gray, 128, 255, cv2.THRESH_BINARY
. The 128 part is called ** threshold **, and here Values brighter than the value of are white (255) and darker values are black (0). This is important for binarizing the threshold value.
Binarization
import numpy as np
pixels = np.array(src)
import matplotlib.pyplot as plt]
#Convert to grayscale
img_gray = cv2.cvtColor(pixels, cv2.COLOR_BGR2GRAY)
#Binarization
retval, img_binary = cv2.threshold(img_gray,128, 255, cv2.THRESH_BINARY)
plt.imshow(img_binary)
Execution result
Threshold = 128
Threshold = 8
Recommended Posts