Stomach_Cancer_Pytorch/analyze_crop_and_stats.py

131 lines
4.0 KiB
Python

import cv2
import numpy as np
import matplotlib.pyplot as plt
import os
import sys
# Add the current directory to sys.path to ensure imports work correctly
sys.path.append(os.getcwd())
from model_data_processing.Crop_And_Fill import Crop_Result
def count_quadrant_pixels(image):
"""
Splits the image into 4 quadrants and counts non-black pixels in each.
Returns a dictionary with counts for TL, TR, BL, BR.
"""
h, w = image.shape[:2]
h_mid, w_mid = h // 2, w // 2
# Convert to grayscale for pixel counting if it's color
if len(image.shape) == 3:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
else:
gray = image
# Threshold to identify non-black pixels (pixel value > 0)
# You can adjust threshold if 'black' isn't perfectly 0
_, mask = cv2.threshold(gray, 1, 255, cv2.THRESH_BINARY)
# Define quadrants
# Top-Left
tl = mask[0:h_mid, 0:w_mid]
# Top-Right
tr = mask[0:h_mid, w_mid:w]
# Bottom-Left
bl = mask[h_mid:h, 0:w_mid]
# Bottom-Right
br = mask[h_mid:h, w_mid:w]
counts = {
'Top-Left': cv2.countNonZero(tl),
'Top-Right': cv2.countNonZero(tr),
'Bottom-Left': cv2.countNonZero(bl),
'Bottom-Right': cv2.countNonZero(br)
}
return counts
def plot_charts(counts, output_dir):
labels = list(counts.keys())
values = list(counts.values())
# Create a figure with 2 subplots
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))
# Bar Chart
colors = ['#FF9999', '#66B2FF', '#99FF99', '#FFCC99']
bars = ax1.bar(labels, values, color=colors)
ax1.set_title('Pixel Count per Quadrant (Bar Chart)')
ax1.set_ylabel('Number of Non-Black Pixels')
# Add value labels on top of bars
for bar in bars:
height = bar.get_height()
ax1.text(bar.get_x() + bar.get_width()/2., height,
f'{height:,}',
ha='center', va='bottom')
# Pie Chart
ax2.pie(values, labels=labels, autopct='%1.1f%%', startangle=90, colors=colors)
ax2.set_title('Pixel Distribution per Quadrant (Pie Chart)')
plt.tight_layout()
chart_path = os.path.join(output_dir, 'quadrant_analysis.png')
plt.savefig(chart_path)
print(f"Charts saved to: {chart_path}")
plt.close()
def main():
# Setup paths
input_image_name = 'a140.jpg' # Example image from root
input_image_path = os.path.abspath(input_image_name)
output_dir = os.path.abspath('crop_output_analysis')
if not os.path.exists(input_image_path):
print(f"Error: Input image {input_image_path} not found.")
# Try to find any jpg file
files = [f for f in os.listdir('.') if f.endswith('.jpg')]
if files:
input_image_path = os.path.abspath(files[0])
print(f"Using alternative image: {input_image_path}")
else:
return
print(f"Processing image: {input_image_path}")
# 1. Run Crop_Result
# Note: Crop_Result expects a list of paths
try:
Crop_Result([input_image_path], output_dir)
except Exception as e:
print(f"Error during cropping: {e}")
return
# 2. Load the cropped result
# The output filename matches the input filename
cropped_image_path = os.path.join(output_dir, os.path.basename(input_image_path))
if not os.path.exists(cropped_image_path):
print(f"Error: Cropped image not found at {cropped_image_path}")
return
print(f"Loading cropped image from: {cropped_image_path}")
cropped_img = cv2.imread(cropped_image_path)
if cropped_img is None:
print("Failed to load cropped image.")
return
# 3. Calculate pixel counts in 4 corners (quadrants)
counts = count_quadrant_pixels(cropped_img)
print("Pixel counts per quadrant:")
for k, v in counts.items():
print(f" {k}: {v}")
# 4. Generate Charts
plot_charts(counts, output_dir)
if __name__ == "__main__":
main()