Python
python展开代码import cv2
class DataConvert():
    """
    表达方式 说明
    x1,y1,x2,y2 (x1,y1)为左上角坐标,(x2,y2)为右下角坐标
    x1,y1,w,h (x1,y1)为左上角坐标,w为目标区域宽度,h为目标区域高度
    xc,yc,w,h (xc,yc)为目标区域中心坐标,w为目标区域宽度,h为目标区域高度 COCO标注
    """
    def __init__(self):
        pass
    @staticmethod
    def cvtx0y0whTox1y1x2y2(x0, y0, w, h, imgShape):
        # "0.530921 0.666667 0.622368 0.666667"=>(167, 169, 639, 507)
        # labelme 的COCO标注格式就是 中心点x+中心点y+宽+高 (归一化的)
        # 此函数出来的就是 左上点  右下点  (未归一化的)
        height, width, c = imgShape
        x1, y1, x2, y2 = int((x0 - w * 0.5) * width), \
                         int((y0 - h * 0.5) * height), \
                         int((x0 + w * 0.5) * width), \
                         int((y0 + h * 0.5) * height)
        return x1, y1, x2, y2
    @staticmethod
    def cvtx1y1x2y2Tox0y0wh(x1, y1, x2, y2, imgShape):
        # (167, 169, 639, 507)=>"0.530921 0.666667 0.622368 0.666667"
        # 左上点  右下点  (未归一化的) => 中心点x+中心点y+宽+高 (归一化的)
        height, width, c = imgShape
        x0, y0, w, h = (x1 + x2) / 2 / width, (y1 + y2) / 2 / height, (x2 - x1) / width, (y2 - y1) / height,
        return x0, y0, w, h
if __name__ == '__main__':
    img = cv2.imread("jg02387.jpg")
    shape = img.shape
    x1, y1, x2, y2 = DataConvert.cvtx0y0whTox1y1x2y2(0.530921, 0.666667, 0.622368, 0.666667, shape)
    print(x1, y1, x2, y2)
    print(DataConvert.cvtx1y1x2y2Tox0y0wh(x1, y1, x2, y2, shape))


本文作者:Dong
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 CC BY-NC。本作品采用《知识共享署名-非商业性使用 4.0 国际许可协议》进行许可。您可以在非商业用途下自由转载和修改,但必须注明出处并提供原作者链接。 许可协议。转载请注明出处!