canopy / plantsdataset.py
Ziyuan111's picture
Update plantsdataset.py
6b56607 verified
raw
history blame
No virus
3.09 kB
from datasets import DatasetInfo, Features, Value, ClassLabel, Split, SplitGenerator, GeneratorBasedBuilder, BuilderConfig
import os
from PIL import Image
import matplotlib.pyplot as plt
import numpy as np
# Rest of your code...
# Google Drive ID for your ZIP file
_DRIVE_ID = "1fXgVwhdU5YGj0SPIcHxSpxkhvRh54oEH"
_URL = f"https://drive.google.com/uc?export=download&id={_DRIVE_ID}"
class PlantsDataset(GeneratorBasedBuilder):
class MyConfig(BuilderConfig):
def __init__(self, **kwargs):
super().__init__(**kwargs)
BUILDER_CONFIGS = [
MyConfig(name="plants_default", description="Default configuration for PlantsDataset"),
]
BUILDER_CONFIGS = [
MyConfig(name="default", description="Default configuration"),
]
def _info(self):
features = Features({
"image": Value("string"),
"label": ClassLabel(names=["aleo vera", "calotropis gigantea"]),
})
return DatasetInfo(
description="Your dataset description",
features=features,
supervised_keys=("image", "label"),
homepage="Your dataset homepage",
citation="Citation for your dataset",
)
def _split_generators(self, dl_manager):
downloaded_file = dl_manager.download_and_extract(_URL)
return [
SplitGenerator(
name=Split.TRAIN,
gen_kwargs={
"data_folder": os.path.join(downloaded_file, "train"),
},
),
SplitGenerator(
name=Split.TEST,
gen_kwargs={
"data_folder": os.path.join(downloaded_file, "test"),
},
),
]
def _generate_examples(self, data_folder):
label_names = self.info.features['label'].names
for label, subfolder in enumerate(label_names):
subfolder_path = os.path.join(data_folder, subfolder)
for root, _, files in os.walk(subfolder_path):
for file_name in files:
file_path = os.path.join(root, file_name)
if os.path.isfile(file_path):
# Open the image using Pillow and convert it to an array
with Image.open(file_path) as image:
image_array = np.array(image)
# Yield the example with the image data and label
yield file_path, {
"image": image_array.tolist(), # Convert array to list
"label": label,
}
def _display_image(self, image_path, label):
with Image.open(image_path) as img:
plt.imshow(img)
plt.title(f"Label: {self.info.features['label'].int2str(label)}")
plt.axis('off') # Hide the axis
plt.show()
# Create an instance of the PlantsDataset class
plants_dataset = PlantsDataset()
# Build and upload the dataset
plants_dataset.download_and_prepare()