分割結果視覺化,把標籤mask輪廓顯示在原圖上

梅雨明夏發表於2024-10-09
import cv2
import numpy as np
from matplotlib import pyplot as plt
from PIL import Image

# Load the original and label images
original_image_path = r'C:\Users\xia94\Desktop\1656\32.png'
label_image_path = r'C:\Users\xia94\Desktop\1656\label.png'

# Load the images
original_img = cv2.imread(original_image_path)
label_img = cv2.imread(label_image_path, cv2.IMREAD_GRAYSCALE)

# Ensure the label image is binary
_, binary_label = cv2.threshold(label_img, 1, 255, cv2.THRESH_BINARY)

# Find contours in the label image
contours, _ = cv2.findContours(binary_label, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# Draw contours on the original image with yellow color and thinner borders
contoured_img = original_img.copy()

# Modify the thickness and color in the following line
cv2.drawContours(contoured_img, contours, -1, (0, 255, 255), 1)  # label contours (BGR format) with thickness 1
# cv2.drawContours(contoured_img, contours, -1, (255,144,30), 1)  #  ct (BGR format) with thickness 1
# cv2.drawContours(contoured_img, contours, -1, (0,255,0), 1)  #  seg3d (BGR format) with thickness 1

# Show the result
plt.figure(figsize=(10, 10))
plt.imshow(cv2.cvtColor(contoured_img, cv2.COLOR_BGR2RGB))
plt.title('Original Image with Yellow Contours')
plt.axis('off')
plt.show()

# Convert the OpenCV image (BGR) to RGB for Pillow
contoured_img_rgb = cv2.cvtColor(contoured_img, cv2.COLOR_BGR2RGB)

# Save the image as a TIFF file with DPI using Pillow
output_tif_path = r'C:\Users\xia94\Desktop\1656\label.tif'
pil_img = Image.fromarray(contoured_img_rgb)
dpi_value = (300, 300)  # Set the DPI (horizontal, vertical)
pil_img.save(output_tif_path, dpi=dpi_value)

相關文章