UOMOP

Image (variance , entropy , edge) 본문

DE/Code

Image (variance , entropy , edge)

Happy PinGu 2024. 8. 5. 13:39
import torch
import torchvision
import torchvision.transforms as tr
import numpy as np
import matplotlib.pyplot as plt
from torchvision import datasets
from torch.utils.data import DataLoader
from skimage.feature import canny
from skimage.measure import shannon_entropy
import cv2

# Transform 설정: 이미지 정규화 및 텐서 변환
transf = tr.Compose([tr.ToTensor()])

# CIFAR-10 데이터셋 불러오기
trainset = torchvision.datasets.CIFAR10(root='./data', train=True, download=True, transform=transf)
trainloader = DataLoader(trainset, batch_size=len(trainset), shuffle=False)

# 이미지와 라벨 추출
images, labels = next(iter(trainloader))
images = images.numpy()

# 엣지 검출량 계산 함수
def calculate_edge_amount(image):
    # 이미지가 3채널(RGB)이면 그레이스케일로 변환
    if image.shape[0] == 3:
        image = np.transpose(image, (1, 2, 0))
        gray_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
    else:
        gray_image = image

    # Canny 엣지 검출 수행
    edges = canny(gray_image)
    return np.sum(edges)  # 검출된 엣지의 수 반환

# 엣지 검출량 계산
edge_amounts = np.array([calculate_edge_amount(img) for img in images])

# 각 이미지의 분산 계산
variances = np.var(images, axis=(1, 2, 3))

# 각 이미지의 엔트로피 계산
entropies = np.array([shannon_entropy(np.transpose(img, (1, 2, 0))) for img in images])

# 엣지 검출량이 높은 순서대로 정렬
sorted_indices = np.argsort(-edge_amounts)
sorted_images = images[sorted_indices]
sorted_edge_amounts = edge_amounts[sorted_indices]
sorted_variances = variances[sorted_indices]
sorted_entropies = entropies[sorted_indices]

# 특정 순위의 이미지 출력 및 정보 표시
def display_image_with_details(rank):
    if rank < 1 or rank > len(sorted_images):
        print(f"Rank must be between 1 and {len(sorted_images)}")
        return

    index = rank - 1
    image = sorted_images[index]
    edge_amount = sorted_edge_amounts[index]
    variance = sorted_variances[index]
    entropy = sorted_entropies[index]

    # 이미지 출력
    plt.imshow(np.transpose(image, (1, 2, 0)))
    plt.title(f"Rank: {rank}, Edge Amount: {edge_amount}, Variance: {variance:.2f}, Entropy: {entropy:.2f}")
    plt.axis('off')
    plt.show()

# 예시: 복잡도 순위 1, 10, 100번째 이미지 출력
display_image_with_details(1)
display_image_with_details(10)
display_image_with_details(100)


# 그래프 그리기

# 그래프 그리기
plt.figure(figsize=(12, 6))
x = np.arange(1, len(sorted_images) + 1)

# 분산과 엔트로피의 스케일링
variance_scaled = sorted_variances * 700
entropy_scaled = sorted_entropies * 20

plt.plot(x, sorted_edge_amounts, label='Edge Amount', color='b')
#plt.plot(x, variance_scaled, label='Scaled Variance', color='g')
plt.plot(x, entropy_scaled, label='Scaled Entropy', color='r')

plt.xlabel('Image Index')
plt.ylabel('Metric Value')
plt.title('Edge Amount, Scaled Variance, and Scaled Entropy Sorted by Edge Amount')
plt.legend()
plt.grid(True)
plt.show()

'DE > Code' 카테고리의 다른 글

Filter counting of zero padding  (0) 2024.08.06
Patch selection code (CBS)  (0) 2024.08.05
CheckerBoard Selection  (0) 2024.07.30
Random Selection  (0) 2024.07.30
Masking comparison (STL10)  (0) 2024.07.29
Comments