|
| 1 | + |
| 2 | +def __convert_annotations_opencv_to_yolo(image_width, image_height, all_points): |
| 3 | + """ |
| 4 | + 0 x1 y1 x2 y2 -> 0 centerX centerY width height |
| 5 | + converts opencv image coordinates to yolo style annotations label of the images has to be included |
| 6 | + """ |
| 7 | + yolo_points = [] |
| 8 | + for points in all_points: |
| 9 | + label = points[0] |
| 10 | + x1 = points[1][0] |
| 11 | + y1 = points[1][1] |
| 12 | + x2 = points[2][0] |
| 13 | + y2 = points[2][1] |
| 14 | + |
| 15 | + w = abs(x1-x2) |
| 16 | + h = abs(y1-y2) |
| 17 | + |
| 18 | + if(x1>x2): |
| 19 | + cx = x1-w/2 |
| 20 | + else: |
| 21 | + cx = x2-w/2 |
| 22 | + |
| 23 | + if(y1>y2): |
| 24 | + cy = y1 - h/2 |
| 25 | + else: |
| 26 | + cy = y2 - h/2 |
| 27 | + |
| 28 | + cx = cx/image_width |
| 29 | + cy = cy/image_height |
| 30 | + |
| 31 | + w = abs(x1-x2)/image_width |
| 32 | + h = abs(y1-y2)/image_height |
| 33 | + |
| 34 | + yolo_points.append((label, cx,cy,w,h)) |
| 35 | + |
| 36 | + return yolo_points |
| 37 | + |
| 38 | + |
| 39 | +def __convert_annotations_yolo_to_opencv(image_width, image_height, all_points): |
| 40 | + """ |
| 41 | + 0 centerX centerY width height -> 0 x1 y1 x2 y2 |
| 42 | + converts yolo style annotations to opencv image coordinates so you can draw rectangles |
| 43 | + it also returns label of the image as first element of the list |
| 44 | + """ |
| 45 | + |
| 46 | + # most of the time this values will be reed from a file and an empty list can cause some problems so I used try catch |
| 47 | + try: |
| 48 | + opencv_points = [] |
| 49 | + for points in all_points: |
| 50 | + # percent to abs pixel positions |
| 51 | + mx = image_width * float(points[1]) |
| 52 | + my = image_height * float(points[2]) |
| 53 | + |
| 54 | + w = image_width * float(points[3]) |
| 55 | + h = image_height * float(points[4]) |
| 56 | + |
| 57 | + # it should be like this in a regular coodinate system but on computer y coordinates are reversed |
| 58 | + # 0,0 is top left instead of bottom left |
| 59 | + # soly = int(my + h/2) sagy = int(my - h/2) |
| 60 | + |
| 61 | + top_left_y = int(my - h/2) |
| 62 | + top_left_x = int(mx - w/2) |
| 63 | + bottom_rigth_y = int(my + h/2) |
| 64 | + bottom_right_x = int(mx + w/2) |
| 65 | + opencv_points.append((int(points[0]), top_left_x, top_left_y, bottom_right_x, bottom_rigth_y)) |
| 66 | + except(IndexError): |
| 67 | + pass |
| 68 | + |
| 69 | + return opencv_points |
| 70 | + |
0 commit comments