Datasets:

Modalities:
Image
Video
Formats:
parquet
Size:
< 1K
Libraries:
Datasets
pandas
License:
FishGrade / README.md
SPovoli's picture
Update README.md
f41adc8 verified
metadata
license: cc-by-nc-4.0
dataset_info:
  features:
    - name: image
      dtype: image
    - name: annotations
      list:
        - name: class_id
          dtype: int64
        - name: segmentation
          sequence:
            sequence:
              sequence: float64
  splits:
    - name: train
      num_bytes: 103638330
      num_examples: 82
    - name: valid
      num_bytes: 26074864
      num_examples: 21
  download_size: 124824112
  dataset_size: 129713194
configs:
  - config_name: default
    data_files:
      - split: train
        path: data/train-*
      - split: valid
        path: data/valid-*

Vision-Guided Robotic System for Automatic Fish Quality Grading and Packaging

This dataset (recorded with a Realsense D456 camera), associated with our work accepted in the IEEE/CAA Journal of Automatica Sinica, includes images and corresponding instance segmentation annotations (in YOLO format) of hake fish steaks on an industrial conveyor belt. It also provides BAG files for two quality grades of fish steaks (A and B), where A-grade steaks are generally larger. The paper details our use of YOLOv8 instance segmentation (check HERE how to train and validate the model) to isolate the fish steaks and the subsequent measurement of their size using the depth data from the BAG files.

πŸ€— [Paper] Coming soon ...

πŸ“½οΈ Demo Video

▢️ Click to Watch

Dataset Structure

πŸ—‚οΈ BAG files & trained segmentation model:

Please first read the associated paper to understand the proposed pipeline.

The BAG files for A and B grades, as well as the weights of the trained segmentation model (best.pt and last.pt), can be found [HERE]..

The segmentation model is designed to segment fish samples. The BAG files are intended for testing purposes. For example, you could use the provided model weights to segment the RGB images within the BAG files and then measure their size based on the depth data.

For clarity, a simplified code snippet for measuring steaks' (metric) perimeter is provided below. You can repurpose this for your specific task:

import pyrealsense2 as rs
import numpy as np
import cv2
import copy
import time
import os
import torch
from ultralytics import YOLO
from random import randint
import math
import matplotlib.pyplot as plt

class ARC:
    def __init__(self):
        bag = r'Class_A_austral.bag' # path of the bag file
        self.start_frame = 0 # start from the this frame to allow the sensor to adjust
        # ROI coordinates are determined from the depth images (checked visually and fixed)
        self.x1_roi, self.x2_roi = 250, 1280
        self.y1_roi, self.y2_roi = 0, 470    
        self.delta = 5 # to discard steaks occluded along the borders of the image
        self.area_tresh = 80 
        self.bag = bag
        self.device = torch.device("cuda") if torch.cuda.is_available() else torch.device("cpu")

        # load and run model
        self.my_model = YOLO('./weights/last.pt') # path of the bag file

        self.pipeline = rs.pipeline()
        config = rs.config()
        config.enable_device_from_file(bag, False)
        config.enable_all_streams()

        profile = self.pipeline.start(config)
        device = profile.get_device()
        playback = device.as_playback()
        playback.set_real_time(False)        

        ####################  POSTPROCESSING  ########################################
        self.fill_filter = rs.hole_filling_filter()
        ##############################################################################

    def video(self):
        align_to = rs.stream.color
        align = rs.align(align_to)

        t_init_wait_for_frames = time.time()
        for i in range(self.start_frame):
            self.pipeline.wait_for_frames()
        t_end_wait_for_frames = time.time()
        i = self.start_frame
        while True:            
            t_init_all = time.time()
            frames = self.pipeline.wait_for_frames()
            aligned_frames = align.process(frames)
            color_frame = aligned_frames.get_color_frame()
            depth_frame = aligned_frames.get_depth_frame()
            self.color_intrin = color_frame.profile.as_video_stream_profile().intrinsics

            # postprocessing, hole filling of depth noise
            depth_frame = self.fill_filter.process(depth_frame).as_depth_frame()

            # if raw depth is used
            self.depth_frame = depth_frame

            # Convert color_frame to numpy array to render image in opencv
            color_image = np.asanyarray(color_frame.get_data())
            rgb_image = cv2.cvtColor(color_image, cv2.COLOR_BGR2RGB)
           
            results = list(self.my_model(rgb_image, conf=0.7, retina_masks=True, verbose=False, device=self.device))
            result = results[0] # The results list may have multiple values, one for each detected object. Because in this example we have only one object in each image, we take the first list item.

            if result.masks == None: # Proceed only if there are detected steaks
                print('---------> Frame {}: No steaks detected'.format(i))
                i += 1
            else: 
                print('---------> Frame {} >> Processing {} steak(s)'.format(i, len(result.masks)))
                masks = result.masks.data
                masks = masks.detach().cpu()
                # resize masks to image size (yolov8 outputs padded masks on top and bottom stripes that are larger in width wrt input image)             
                padding_width = int((masks.shape[1] - rgb_image.shape[0])/2)
                masks = masks[:, padding_width:masks.shape[1]-padding_width, :]

                # filter out the masks that lie at the predefined (above) ROI (e.g., occluded fish steaks, because they cannot be graded if not whole) 
                id_del = []
                for id_, msk in enumerate(masks):
                    x_coord = np.nonzero(msk)[:, 1]
                    y_coord = np.nonzero(msk)[:, 0]
                    # ROI
                    x_del1 = x_coord <= self.x1_roi + self.delta
                    x_del2 = x_coord >= self.x2_roi - self.delta
                    if True in x_del1 or True in x_del2:
                        id_del.append(id_)
                        del x_del1, x_del2   
                id_keep = list(range(masks.shape[0]))
                id_keep = [item for item in id_keep if item not in id_del]
                masks = masks[id_keep]

                # calculate the perimeter of each object ############################################################################################ PERIMETER
                polygons = result.masks.xyn
                # scale the yolo format polygon coordinates by image width and height
                for pol in polygons:
                    for point_id in range(len(pol)):
                        pol[point_id][0] *= rgb_image.shape[1] 
                        pol[point_id][1] *= rgb_image.shape[0]
                polygons = [polygons[item] for item in id_keep]        
                t_init_perimeter = time.time()
                perimeters = [0]*len(polygons)
                for p in range(len(polygons)): # the polygon (mask) id
                    step = 5  # dist measurement step between polygon points
                    for point_id in range(0, len(polygons[p])-step, step):
                        x1 = round(polygons[p][point_id][0])
                        y1 = round(polygons[p][point_id][1])
                        x2 = round(polygons[p][point_id + step][0])
                        y2 = round(polygons[p][point_id + step][1])

                        # calculate_distance between polygon points
                        dist = self.calculate_distance(x1, y1, x2, y2)
                        # print('> x1, y1, x2, y2:  {},  {},  {},  {}'.format(x1, y1, x2, y2), '--- distance between the 2 points: {0:.10} cm'.format(dist))

                        # # visualise the points on the image
                        # image_points = copy.deepcopy(rgb_image)
                        # image_points = cv2.circle(image_points, (x1,y1), radius=3, color=(0, 0, 255), thickness=-1)
                        # image_points = cv2.circle(image_points, (x2,y2), radius=3, color=(0, 255, 0), thickness=-1)
                        # image_points = cv2.putText(image_points, 'Distance {} cm'.format(dist), org = (50, 50) , fontFace = cv2.FONT_HERSHEY_SIMPLEX , fontScale = 1, color = (255, 0, 0) , thickness = 2)
                        # cv2.imshow('image_points' + str(id_), image_points)
                        # cv2.waitKey(0)
                        # cv2.destroyAllWindows()  

                        # accumulate the distance in cm
                        perimeters[p] += dist
                        perimeters[p] = round(perimeters[p], 2)
                        del dist, x1, y1, x2, y2
                i += 1

    def calculate_distance(self, x1, y1, x2, y2):
        color_intrin = self.color_intrin
        udist = self.depth_frame.get_distance(x1, y1)
        vdist = self.depth_frame.get_distance(x2, y2)
        # print udist, vdist
        point1 = rs.rs2_deproject_pixel_to_point(color_intrin, [x1, y1], udist)
        point2 = rs.rs2_deproject_pixel_to_point(color_intrin, [x2, y2], vdist)

        dist = math.sqrt(math.pow(point1[0] - point2[0], 2) + math.pow(point1[1] - point2[1],2) + math.pow(point1[2] - point2[2], 2))
        return round(dist*100, 2)   # multiply by 100 to convert m to cm

if __name__ == '__main__':
    ARC().video()

πŸ—‚οΈ Data Instances

Raspberry Example 1 Raspberry Example 2

🏷️ Annotation Format

Note that the annotations follow the YOLO instance segmentation format.

Please refer to this page for more info.

πŸ§ͺ How to read and display examples

from datasets import load_dataset
import matplotlib.pyplot as plt
import random
import numpy as np

def show_example(dataset):
    example = dataset[random.randint(0, len(dataset) - 1)]
    image = example["image"].convert("RGB")
    annotations = example["annotations"]
    width, height = image.size

    fig, ax = plt.subplots(1)
    ax.imshow(image)

    num_instances = len(annotations)
    colors = plt.cm.get_cmap('viridis', num_instances)

    if annotations:
        for i, annotation in enumerate(annotations):
            class_id = annotation["class_id"]
            segmentation = annotation.get("segmentation")
            if segmentation and len(segmentation) > 0:
                polygon_norm = segmentation[0]
                if polygon_norm:
                    polygon_abs = np.array([(p[0] * width, p[1] * height) for p in polygon_norm])
                    x, y = polygon_abs[:, 0], polygon_abs[:, 1]
                    color = colors(i)
                    ax.fill(x, y, color=color, alpha=0.5)

    plt.title(f"Example with {len(annotations)} instances")
    plt.axis('off')
    plt.show()

if __name__ == "__main__":
    dataset_name = "MohamedTEV/FishGrade"
    try:
        fish_dataset = load_dataset(dataset_name, split="train")
        print(fish_dataset)
        show_example(fish_dataset)
    except Exception as e:
        print(f"Error loading or displaying the dataset: {e}")
        print(f"Make sure the dataset '{dataset_name}' exists and is public, or you are logged in if it's private.")

πŸ™ Acknowledgement

AGILEHAND logo

This work is supported by European Union’s Horizon Europe research and innovation programme under grant agreement No 101092043, project AGILEHAND (Smart Grading, Handling and Packaging Solutions for Soft and Deformable Products in Agile and Reconfigurable Lines).

🀝 Partners

FBK logo FBK logo FBK logo Produmar logo

πŸ“– Citation

Coming soon ... ```