import cv2 from PIL import Image import numpy as np import matplotlib.pyplot as plt Load…
- User
import cv2 from PIL import Image import numpy as np import matplotlib.pyplot as plt
Load the image
image_path = '/Users/abhi/Downloads/Zerodur/Sample 3_Fine.tif' image = Image.open(image_path)
Convert to grayscale
gray_image = np.array(image.convert("L"))
Perform binarization using Otsu's method
_, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
Increase DPI for higher resolution output
fig, axes = plt.subplots(1, 2, figsize=(12, 6), dpi=150)
axes[0].imshow(gray_image, cmap='gray') axes[0].set_title('Grayscale Image') axes[0].axis('off')
axes[1].imshow(binary_image, cmap='gray') axes[1].set_title('Binary Image') axes[1].axis('off')
plt.show()
Show original image and Binary image, not the grayscale image
- Assistant
To display the original image and the binary image side by side (instead of grayscale and binary), you just need to plot the original image on the left and binary image on the right.
Since your original image is loaded with PIL, it might be in color (RGB) or grayscale depending on your TIFF. Here's the updated code where the original image will be displayed on the left, and the binary image on the right:
import cv2 from PIL import Image import numpy as np import matplotlib.pyplot as plt # Load the image image_path = '/Users/abhi/Downloads/Zerodur/Sample 3_Fine.tif' image = Image.open(image_path) # Convert to grayscale for thresholding gray_image = np.array(image.convert("L")) # Perform binarization using Otsu's method _, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) # Increase DPI for higher resolution output fig, axes = plt.subplots(1, 2, figsize=(12, 6), dpi=150) # Show original image (convert to numpy array for imshow) axes[0].imshow(np.array(image)) axes[0].set_title('Original Image') axes[0].axis('off') axes[1].imshow(binary_image, cmap='gray') axes[1].set_title('Binary Image') axes[1].axis('off') plt.show()