| import os |
| import torch |
| from tqdm import tqdm |
| from PIL import Image |
| from transformers import AutoModel, AutoTokenizer |
| import torchvision.transforms as T |
| from torchvision.transforms.functional import InterpolationMode |
|
|
|
|
| IMAGENET_MEAN = (0.485, 0.456, 0.406) |
| IMAGENET_STD = (0.229, 0.224, 0.225) |
|
|
|
|
| def build_transform(input_size): |
| return T.Compose([ |
| T.Lambda(lambda img: img.convert('RGB') if img.mode != 'RGB' else img), |
| T.Resize((input_size, input_size), interpolation=InterpolationMode.BICUBIC), |
| T.ToTensor(), |
| T.Normalize(mean=IMAGENET_MEAN, std=IMAGENET_STD) |
| ]) |
|
|
| def find_closest_aspect_ratio(aspect_ratio, target_ratios, width, height, image_size): |
| best_ratio_diff = float('inf') |
| best_ratio = (1, 1) |
| area = width * height |
| for ratio in target_ratios: |
| target_aspect_ratio = ratio[0] / ratio[1] |
| ratio_diff = abs(aspect_ratio - target_aspect_ratio) |
| if ratio_diff < best_ratio_diff: |
| best_ratio_diff = ratio_diff |
| best_ratio = ratio |
| elif ratio_diff == best_ratio_diff: |
| if area > 0.5 * image_size * image_size * ratio[0] * ratio[1]: |
| best_ratio = ratio |
| return best_ratio |
|
|
| def dynamic_preprocess(image, min_num=1, max_num=12, image_size=448, use_thumbnail=False): |
| orig_width, orig_height = image.size |
| aspect_ratio = orig_width / orig_height |
| target_ratios = sorted( |
| [(i, j) for n in range(min_num, max_num + 1) for i in range(1, n + 1) |
| for j in range(1, n + 1) if i * j <= max_num and i * j >= min_num], |
| key=lambda x: x[0] * x[1] |
| ) |
| target_aspect_ratio = find_closest_aspect_ratio(aspect_ratio, target_ratios, orig_width, orig_height, image_size) |
| target_width = image_size * target_aspect_ratio[0] |
| target_height = image_size * target_aspect_ratio[1] |
| blocks = target_aspect_ratio[0] * target_aspect_ratio[1] |
| resized_img = image.resize((target_width, target_height)) |
| processed_images = [] |
| for i in range(blocks): |
| box = ( |
| (i % (target_width // image_size)) * image_size, |
| (i // (target_width // image_size)) * image_size, |
| ((i % (target_width // image_size)) + 1) * image_size, |
| ((i // (target_width // image_size)) + 1) * image_size |
| ) |
| processed_images.append(resized_img.crop(box)) |
| if use_thumbnail and len(processed_images) != 1: |
| thumbnail_img = image.resize((image_size, image_size)) |
| processed_images.append(thumbnail_img) |
| return processed_images |
|
|
| def load_image(image_file, input_size=448, max_num=12): |
| image = Image.open(image_file).convert('RGB') |
| transform = build_transform(input_size) |
| images = dynamic_preprocess(image, image_size=input_size, use_thumbnail=True, max_num=max_num) |
| return torch.stack([transform(img) for img in images]) |
|
|
|
|
| model_path = 'OpenGVLab/InternVL2_5-4B' |
| model = AutoModel.from_pretrained( |
| model_path, |
| torch_dtype=torch.bfloat16, |
| low_cpu_mem_usage=True, |
| use_flash_attn=True, |
| cache_dir="./", |
| trust_remote_code=True |
| ).eval().cuda() |
| tokenizer = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True, use_fast=False) |
|
|
|
|
| question = ( |
| '''<image>\n |
| 1. Identify the type of fruit or crop shown in the image. |
| 2. Determine its current growth stage. (Options: unripe, mature, pest-damaged, rotten) |
| 3. Recommend the farmer’s next action. (Options: keep for further growth, try to recover it, discard it) |
| 4. Evaluate the consumer’s willingness to consume this fruit, from 1 (very unlikely) to 100 (very likely). |
| Please respond in the following format: |
| Type: [Fruit/Crop Name] Growth Stage: [unripe / mature / pest-damaged / rotten] Recommendation: [keep for further growth / pick it / try to recover it / discard it] Consumer Score: [1-100] |
| ''' |
| ) |
|
|
|
|
| generation_config = dict(max_new_tokens=1024, do_sample=True) |
|
|
|
|
| root_folder = "../data" |
| output_root = "result" |
| os.makedirs(output_root, exist_ok=True) |
|
|
|
|
| for fruit in os.listdir(root_folder): |
| fruit_path = os.path.join(root_folder, fruit) |
| if not os.path.isdir(fruit_path): continue |
|
|
| for subfolder in os.listdir(fruit_path): |
| subfolder_path = os.path.join(fruit_path, subfolder) |
| if not os.path.isdir(subfolder_path): continue |
|
|
| image_files = [f for f in os.listdir(subfolder_path) |
| if f.lower().endswith(('.jpg', '.jpeg', '.png', '.bmp'))] |
| if not image_files: |
| continue |
|
|
| output_file = os.path.join(output_root, f"{fruit}_{subfolder}.txt") |
| |
| with open(output_file, "w", encoding="utf-8") as out_file: |
| for image_file in tqdm(image_files, desc=f"{fruit}/{subfolder}"): |
| image_path = os.path.join(subfolder_path, image_file) |
| try: |
| pixel_values = load_image(image_path).to(torch.bfloat16).cuda() |
| response = model.chat(tokenizer, pixel_values, question, generation_config) |
|
|
| print(f"{image_file} ✅ -> {response}") |
| out_file.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| out_file.write(f"🖼️ Image Name: {image_file}\n") |
| out_file.write(f"📝 Answer:\n{response.strip()}\n") |
| out_file.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
| except Exception as e: |
| print(f"[ERROR] {fruit}/{subfolder}/{image_file}: {e}") |
| out_file.write(f"{'=' * 25} IMAGE START {'=' * 25}\n") |
| out_file.write(f"🖼️ Image Name: {image_file}\n") |
| out_file.write(f"❌ ERROR:\n{e}\n") |
| out_file.write(f"{'=' * 25} IMAGE END {'=' * 25}\n\n") |
|
|