Skip to content

Commit ad9b1eb

Browse files
committed
create_masks_from_polygons func
1 parent 75aee77 commit ad9b1eb

2 files changed

Lines changed: 47 additions & 2 deletions

File tree

patched_yolo_infer/__init__.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
1-
from .functions_extra import visualize_results_usual_yolo_inference, get_crops, visualize_results
1+
from .functions_extra import (
2+
visualize_results_usual_yolo_inference,
3+
get_crops,
4+
visualize_results,
5+
create_masks_from_polygons,
6+
)
27

38
from .nodes.MakeCropsDetectThem import MakeCropsDetectThem
49
from .nodes.CombineDetections import CombineDetections
5-
from .elements.CropElement import CropElement
10+
from .elements.CropElement import CropElement

patched_yolo_infer/functions_extra.py

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -420,3 +420,43 @@ def visualize_results(
420420
if axis_off:
421421
plt.axis('off')
422422
plt.show()
423+
424+
425+
def create_masks_from_polygons(polygons, image):
426+
"""
427+
Create binary masks from a list of polygons.
428+
429+
This function takes a list of polygons and an image, and generates binary masks
430+
where each mask corresponds to one polygon. The masks are boolean arrays with
431+
the same dimensions as the input image, where the regions covered by the polygons
432+
are marked as True.
433+
434+
Parameters:
435+
polygons (list of numpy.ndarray): A list of polygons, where each polygon is
436+
represented as a numpy array of shape (N, 2) containing N (x, y) coordinates.
437+
image (numpy.ndarray): The input image, used to determine the dimensions of the masks.
438+
439+
Returns:
440+
list of numpy.ndarray: A list of binary masks, where each mask is a boolean
441+
numpy array of the same dimensions as the input image.
442+
"""
443+
# Get the dimensions of the image
444+
height, width = image.shape[:2]
445+
446+
# Create empty masks
447+
masks = []
448+
449+
for polygon in polygons:
450+
if len(polygon) > 0:
451+
points = np.array(polygon.reshape((-1, 1, 2)), dtype=np.int32)
452+
453+
# Create an empty mask with the same size as the image
454+
mask = np.zeros((height, width), dtype=np.uint8)
455+
456+
# Draw the polygon on the mask
457+
cv2.fillPoly(mask, [points], 1)
458+
459+
# Add the mask to the list
460+
masks.append(mask)
461+
462+
return masks

0 commit comments

Comments
 (0)