LeoZhangzaolin commited on
Commit
a36eb47
1 Parent(s): 68915fb

Update DataClean and ImageTransfer.py

Browse files
Files changed (1) hide show
  1. DataClean and ImageTransfer.py +29 -39
DataClean and ImageTransfer.py CHANGED
@@ -1,17 +1,21 @@
1
- #### This code shows how I process the data and transfer the images to Numpy arrays on local. After processing, I upload the final csv to github and get the URL.
 
 
 
2
  import csv
3
  import os
4
- import numpy as np
5
- from PIL import Image
6
  import pandas as pd
7
 
8
  # --- Initial Setup ---
9
- initial_csv_file_path = 'https://raw.githubusercontent.com/LeoZhangzaolin/photos/main/Graptolite%20specimens.csv'
10
- columns_to_delete = [
11
- "species ID", "Phylum", "Class", "Order", "revised species name",
12
- "total number of specimens", "specimens Serial No", "显微镜照片数量", "SLR photo No",
13
- "相机照片数量", "跑数据照片总数", "备注", "age from", "age to", "collection No", "Microscrope photo No"
14
- ]
 
 
15
 
16
  # --- Read and Process CSV Data ---
17
  with open(initial_csv_file_path, newline='', encoding='utf-8') as file:
@@ -60,49 +64,35 @@ for row in data[1:]:
60
  # Convert processed data into a DataFrame
61
  df = pd.DataFrame(data[1:], columns=header)
62
 
63
- # --- Image Processing ---
64
- # Image directories
65
- image_dir_paths = ['/Users/leozhangzaolin/Desktop/project 1/graptolite specimens with scale 1',
66
- '/Users/leozhangzaolin/Desktop/project 1/graptolite specimens with scale 2']
67
-
68
- # Normalize file extensions in the image directories
69
- def normalize_file_extensions(dir_path):
70
- for filename in os.listdir(dir_path):
71
- if filename.lower().endswith('.jpg') and not filename.endswith('.jpg'):
72
- base, ext = os.path.splitext(filename)
73
- new_filename = base + '.jpg'
74
- os.rename(os.path.join(dir_path, filename), os.path.join(dir_path, new_filename))
75
-
76
- for path in image_dir_paths:
77
- normalize_file_extensions(path)
78
-
79
- # Function to process and return the image array
80
- def process_image_array(image_name, max_size=(1024, 1024)):
81
  image_base_name = os.path.splitext(image_name)[0]
82
  image_paths = [os.path.join(dir_path, image_base_name + suffix)
83
  for dir_path in image_dir_paths
84
- for suffix in ['_S.jpg', '_S.JPG']]
85
 
86
  image_path = next((path for path in image_paths if os.path.exists(path)), None)
87
 
88
  if image_path is None:
89
  return None
90
 
91
- with Image.open(image_path) as img:
92
- img.thumbnail(max_size, Image.Resampling.LANCZOS)
93
- return np.array(img)
94
 
95
- # Apply the function to embed image arrays in the 'image file name' column
96
- df['image file name'] = df['image file name'].apply(process_image_array)
97
- df = df.dropna(subset=['image file name'])
98
 
99
- # Since arrays can't be directly saved in CSV, convert them to a string representation
100
- df['image file name'] = df['image file name'].apply(lambda x: np.array2string(x))
 
 
 
101
 
102
  # Rename the 'image file name' column to 'image'
103
  df.rename(columns={'image file name': 'image'}, inplace=True)
104
 
105
- # --- Save the Final DataFrame to a CSV File ---
106
- final_csv_path = '/Users/leozhangzaolin/Desktop/Final_GS_with_Images.csv'
107
  df.to_csv(final_csv_path, index=False)
108
-
 
1
+ #### Firstly, I read specimen data from a CSV file, merges and reformats certain columns, and then converts this data into a pandas DataFrame.
2
+ #### Then, I process associated images by resizing them and saving them in a specified output directory.
3
+ #### Next, I update the DataFrame with the paths to the processed images and save this enhanced dataset as a new CSV file.
4
+
5
  import csv
6
  import os
7
+ import cv2
 
8
  import pandas as pd
9
 
10
  # --- Initial Setup ---
11
+ initial_csv_file_path = '/Users/leozhangzaolin/Desktop/Graptolite specimens.csv'
12
+ image_dir_paths = ['/Users/leozhangzaolin/Desktop/project 1/graptolite specimens with scale 1',
13
+ '/Users/leozhangzaolin/Desktop/project 1/graptolite specimens with scale 2']
14
+ output_image_dir = '/Users/leozhangzaolin/Desktop/project 1/output_images'
15
+ target_size = (256, 256)
16
+
17
+ # Ensure output directory exists
18
+ os.makedirs(output_image_dir, exist_ok=True)
19
 
20
  # --- Read and Process CSV Data ---
21
  with open(initial_csv_file_path, newline='', encoding='utf-8') as file:
 
64
  # Convert processed data into a DataFrame
65
  df = pd.DataFrame(data[1:], columns=header)
66
 
67
+ # Function to process and save the image, then return the file path
68
+ def process_and_save_image(image_name, max_size=target_size):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  image_base_name = os.path.splitext(image_name)[0]
70
  image_paths = [os.path.join(dir_path, image_base_name + suffix)
71
  for dir_path in image_dir_paths
72
+ for suffix in ['_S.jpg', '_S.JPG']]
73
 
74
  image_path = next((path for path in image_paths if os.path.exists(path)), None)
75
 
76
  if image_path is None:
77
  return None
78
 
79
+ # Read and resize the image
80
+ img = cv2.imread(image_path, cv2.IMREAD_COLOR)
81
+ img = cv2.resize(img, max_size, interpolation=cv2.INTER_AREA)
82
 
83
+ # Save the image to the output directory
84
+ output_path = os.path.join(output_image_dir, image_base_name + '.jpg')
85
+ cv2.imwrite(output_path, img)
86
 
87
+ return output_path
88
+
89
+ # Apply the function to process images and update the DataFrame
90
+ df['image file name'] = df['image file name'].apply(process_and_save_image)
91
+ df = df.dropna(subset=['image file name'])
92
 
93
  # Rename the 'image file name' column to 'image'
94
  df.rename(columns={'image file name': 'image'}, inplace=True)
95
 
96
+ # Save the DataFrame to a CSV file
97
+ final_csv_path = '/Users/leozhangzaolin/Desktop/Final_GS_with_Images5.csv'
98
  df.to_csv(final_csv_path, index=False)