Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added getpolygons function for Image segmentation with labelbox json (Sourcery refactored) #41

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions labelbox_json2yolo.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,35 @@

from utils import make_dirs

def getPolygons(url):
# Download the image from the URL
with urllib.request.urlopen(url) as url_response:
img_array = np.asarray(bytearray(url_response.read()), dtype=np.uint8)
image = cv2.imdecode(img_array, cv2.IMREAD_COLOR)

h, w = image.shape[:2]
line_width = int((h + w) * 0.5 * 0.0025)
#convert to grayscale
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
contours, _ = cv2.findContours(gray_image, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_TC89_KCOS)

contours_approx = []
polygons = []
#Get polygons
for contour in contours:
epsilon = 0.001 * cv2.arcLength(contour, True)
contour_approx = cv2.approxPolyDP(contour, epsilon, True)

contours_approx.append(contour_approx)
polygon = (contour_approx.flatten().reshape(-1, 2) / np.array([w, h])).tolist()
polygons.append(polygon)
cv2.drawContours(image, contours_approx, -1, 128, line_width)
#format the data correctly
result = [[f"{x},{y}" for x, y in sublist] for sublist in polygons]
return [
[float(x) for pair in sublist for x in pair.split(',')]
for sublist in result
]

def convert(file, zip=True):
# Convert Labelbox JSON labels to YOLO labels
Expand All @@ -26,6 +55,36 @@ def convert(file, zip=True):
image_path = save_dir / 'images' / img['External ID']
im.save(image_path, quality=95, subsampling=0)


######################################
#for Image Segmentation
######################################

# for img in tqdm(data, desc=f'Converting {file}'):
# im_path = img['Labeled Data']
# im = Image.open(requests.get(im_path, stream=True).raw if im_path.startswith('http') else im_path) # open
# width, height = im.size # image size
# label_path = save_dir / 'labels' / Path(img['External ID']).with_suffix('.txt').name
# print(label_path)
# image_path = save_dir / 'images' / img['External ID']
# print(image_path)
# im.save(image_path, quality=95, subsampling=0)

# for label in img['Label']['objects']:
#
# polygon = getPolygons(label['instanceURI'])
# # class
# cls = label['value'] # class name
# if cls not in names:
# names.append(cls)

# line = names.index(cls), *polygon[0] # YOLO format (class_index, polygon)
# with open(label_path, 'a') as f:
# f.write(('%g ' * len(line)).rstrip() % line + '\n')

######################################
#for Object detection
######################################
for label in img['Label']['objects']:
# box
top, left, h, w = label['bbox'].values() # top, left, height, width
Expand Down