The continuation of the article I wrote earlier for the first time in a year. -Image processing with Python (1) -Image processing with Python (2)
The place to binarize using OpenCV is that I wrote the OpenCV document as it is, Image processing with Python (1). Instead of "binarizing", try something like "find the threshold value for binarization and cut off the pixels below that threshold value".
Decrease the image of lenna by 2.
import cv2
lenna = "4.2.04.tiff"
orig = cv2.imread(lenna, 0)
img = cv2.medianBlur(orig, 5)
ret,th = cv2.threshold(img, 0, 255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)
In the image where th is binarized, ret is the threshold value.
If you think simply, it seems that you can do it with the following code.
height, width = img.shape
for y in range(height):
for x in range(width):
if img[y, x] < ret:
img[y, x] = 0
However, there is a problem with this code. Applying for to a numpy array is really slow.
So is there a way to make it faster? Of course there is.
low_idx = img < ret
img[low_idx] = 0
Now, when you compare the images, it looks like this.
from matplotlib import pyplot as plt
plt.subplot(1,3,1)
plt.imshow(orig, cmap='gray'), plt.title('Original')
plt.subplot(1,3,2)
plt.imshow(img, cmap='gray'), plt.title('Threshold')
plt.subplot(1,3,3)
plt.imshow(th, cmap='gray'), plt.title('Binarize')
plt.show()
I found the threshold for binarization and cut off at that threshold.
Recommended Posts