PIWM / npy_reader.py
musictimer's picture
Fix initial bugs
02c6351
raw
history blame
2.65 kB
import numpy as np
import os
import sys
def read_npy_file(file_path):
"""
Read a .npy file and return the numpy array.
Args:
file_path (str): Path to the .npy file
Returns:
numpy.ndarray: The loaded numpy array
Raises:
FileNotFoundError: If the file doesn't exist
ValueError: If the file is not a valid .npy file
"""
try:
# Check if file exists
if not os.path.exists(file_path):
raise FileNotFoundError(f"File not found: {file_path}")
# Check if file has .npy extension
if not file_path.lower().endswith('.npy'):
print(f"Warning: File {file_path} doesn't have .npy extension")
# Load the numpy array
array = np.load(file_path)
print(f"Successfully loaded {file_path}")
print(f"Array shape: {array.shape}")
print(f"Array dtype: {array.dtype}")
print(f"Array size: {array.size}")
return array
except Exception as e:
raise ValueError(f"Error reading {file_path}: {str(e)}")
def print_array_info(array, show_data=False, max_elements=10):
"""
Print detailed information about a numpy array.
Args:
array (numpy.ndarray): The numpy array to analyze
show_data (bool): Whether to show actual data values
max_elements (int): Maximum number of elements to display
"""
print("\n" + "="*50)
print("ARRAY INFORMATION")
print("="*50)
print(f"Shape: {array.shape}")
print(f"Dtype: {array.dtype}")
print(f"Size: {array.size}")
print(f"Dimensions: {array.ndim}")
print(f"Memory usage: {array.nbytes} bytes")
if array.size > 0:
print(f"Min value: {np.min(array)}")
print(f"Max value: {np.max(array)}")
print(f"Mean value: {np.mean(array)}")
print(f"Std deviation: {np.std(array)}")
if show_data:
print("\nArray data:")
if array.size <= max_elements:
print(array)
else:
print(f"First {max_elements} elements:")
print(array.flat[:max_elements])
print("...")
def main():
"""
Main function to demonstrate usage.
"""
file_path = "/home/alienware3/Documents/diamond/low_res.npy"
try:
# Read the NPY file
array = read_npy_file(file_path)
# Print detailed information
print_array_info(array, show_data=True, max_elements=20)
except Exception as e:
print(f"Error: {e}")
sys.exit(1)
if __name__ == "__main__":
main()