Git Product home page Git Product logo

rotated_iou's Introduction

Differentiable IoU of Oriented Boxes

image (image source: here)

Introduction

This repo is an unofficial implementation of IoU Loss for 2D/3D Object Detection. It contains the Pytorch function which calculates the intersection area of oriented rectangles using GPU.

Note

The CUDA extension is modified recently to cover some corner cases. Please consider to update the code and re-compile the extension.

Check List

  • Pytorch function to find intersection points of oriented rectangles
  • Pytorch function to check if corners of one rectangle lie in another
  • CUDA extension to anti-clockwise sort vertices of the intersection polygon of two rectangles
  • Pytorch function to calculate the intersection of area of rectangles using functions above
  • Test cases
  • Rotated 2d/3d GIoU and DIoU loss
  • Demo to validate the back-propagation
  • Validate 2d/3d IoU loss in Object detection

Requirements

Code is tested on Ubuntu 18.04. Following dependencies are needed

cudatoolkit=10.2
pytorch=1.5         # newer version should work as well
numpy
matplotlib
argparse

Usage

First, compile the CUDA extension.

cd cuda_op
python setup.py install

Then, run a demo which validate the Pytorch functions and CUDA extension.

cd ..
python demo.py

This demo trains a network which takes N set of box corners and predicts the x, y, w, h and angle of each rotated boxes. In order to do the back-prop, the predicted box parameters and the GT are converted to coordinates of box corners. The area of intersection is calculated using the Pytorch function with CUDA extension. Then, the GIoU loss or DIoU loss can be calculated. This demo first generates data and then do the training.

You are expected to see some information like followings:

... generating 819200 boxes, please wait...
... generating 81920 boxes, please wait...
data saved in:  ./data
[Epoch 1: 10/200] train loss: 0.6721  mean_iou: 0.3703
[Epoch 1: 20/200] train loss: 0.4931  mean_iou: 0.5211
[Epoch 1: 30/200] train loss: 0.4532  mean_iou: 0.5546
[Epoch 1: 40/200] train loss: 0.4249  mean_iou: 0.5805
[Epoch 1: 50/200] train loss: 0.4361  mean_iou: 0.5713
[Epoch 1: 60/200] train loss: 0.4148  mean_iou: 0.5910
[Epoch 1: 70/200] train loss: 0.4272  mean_iou: 0.5803
[Epoch 1: 80/200] train loss: 0.4283  mean_iou: 0.5801
[Epoch 1: 90/200] train loss: 0.4203  mean_iou: 0.5879

Note the train loss drops and the mean_iou increases, which shows the functions are differentiable.

GIoU and DIoU

This repo implements both GIoU-loss and DIoU-loss for rotated bounding boxes. In the demo, they can be chosen with

python demo.py --loss giou      
python demo.py --loss diou      # [default]

Both losses need the smallest enclosing box of two boxes. Note there are different choices to determin the enclosing box.

  1. axis-aligned box: the enclosing box is axis-aligned. This version is simple and fast but theortically non-optimal.
  2. rotated box (approximated): the enclosing box is rotated as well. The size of rotated enclosing box can be estimated using PCA. The calculation if relatively simple but the result is not accurate. In the demo, this methode seems work well.
  3. rotated box (accurate): real smallest enclosing bounding box. Since the brutal force search is used to get the minimum bounding box, the computational cost is high.

The three types of enclosing box can be chosen with:

python demo.py --enclosing aligned      # simple and naive. bad performance.
python demo.py --enclosing pca          # approximated smallest box. slightly worse performance.
python demo.py --enclosing smallest     # [default]. smallest box. best performance.

Acknowledgement

The idea of calculating intersection area is inspired by this paper:

@INPROCEEDINGS{8886046,
    author={D. {Zhou} and J. {Fang} and X. {Song} and C. {Guan} and J. {Yin} and Y. {Dai} and R. {Yang}},
    booktitle={2019 International Conference on 3D Vision (3DV)}, 
    title={IoU Loss for 2D/3D Object Detection}, 
    year={2019},
    pages={85-94},}

Some code for CUDA extension is modified from:

@article{pytorchpointnet++,
    Author = {Erik Wijmans},
    Title = {Pointnet++ Pytorch},
    Journal = {https://github.com/erikwijmans/Pointnet2_PyTorch},
    Year = {2018}
}

rotated_iou's People

Contributors

lilanxiao avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

rotated_iou's Issues

Use on KITTI dataset labels

Hello, I've a question, You assumed the coordinates x to left y to forward z to up, but I want to use it on KITTI labels, where the labels coordinates are like: x to left y to down z to forward and the rotation ry is around y-axis, so can you help me to figure it out, will I switch the order of the input to the cal_iou_3d or what !?

Inaccurate IoU in some cases

Hi, this repo is very useful for me! But when I test for the accuracy, I find in one case the result of oriented_box_intersection_2d is wrong.

box1 = [4,5,8,10,0]
box2 = [3,4,6,8,0]

The test results in test_box_intersection_2d.py:
CUDA:
[[56. 80.]
[56. 80.]]
[[ 6. 8.]
[ 0. 8.]
[ 0. 0.]
[ 6. 0.]
[ 8. 10.]
[ 6. 8.]
[ 0. 0.]
[ 0. 0.]
[ 0. 0.]]

Numpy:
48.0
[[ 3.6 4.8]
[-2.4 4.8]
[-2.4 -3.2]
[-2.4 -3.2]
[ 3.6 -3.2]]

obviously, the correct result is 48.0

box3d的维度(x,y,z,l,w,h,alpha)

您好,请问在cal_iou里面,定义box3d的维度(x,y,z,w,h,l,alpha),请问这里x是跟w对应的吗?y跟h对应?z跟l对应?因为通常来说,x是跟l对应的,y对应w, z对应h.

    box3d1 (torch.Tensor): (B, N, 3+3+1),  (x,y,z,l,w,h,alpha)
    box3d2 (torch.Tensor): (B, N, 3+3+1),  (x,y,z,l,w,h,alpha)

Bug in cal_dious_3d function

.Bug was found when I use the cal_iou_3d() . IoU result of two bbox3d will get wrong when the angle = np.pi/4 , but get correct when the angle = np.pi/4 + 1e-6. Following is my test case:

import torch
from oriented_iou_loss import cal_diou_3d

x = torch.tensor([0., 0., 0., 2., 2., 2., np.pi/4]
                 ).view(1, 1, 7).cuda()
y = torch.tensor([0., 0., 0., 2., 2., 2., -np.pi/4]).view(1, 1, 7).cuda()

_, iou3d = cal_diou_3d(x, y)
## iou3d = 0 , wrong

x = torch.tensor([0., 0., 0., 2., 2., 2., np.pi/4+1e-6]
                 ).view(1, 1, 7).cuda()
y = torch.tensor([0., 0., 0., 2., 2., 2., -np.pi/4+1e-6]).view(1, 1, 7).cuda()

_, iou3d = cal_diou_3d(x, y)
## iou3d =1, Right

PyTorch1.2 and CUDA10.0

Hi, thanks for your great job.
I encountered some bugs in environment configuration: when I ran 'python set_up.py install', the error occured as follows. Due to some configurations in my machine, the pytorch and cuda verision must be 1.2 and 10.0.

So, does the code support such low-version environment setting? Or, how to modify the code to match my system environment?
I am not familiar with CUDA or C/C++ compilation, and I really need your helps.

Thanks in advanced.

incorrect iou?

Hi @lilanxiao ,

Maybe I'm missing something but:

device = torch.device('cuda:0')
box_0 = torch.tensor([.0, .0, 2., 2., .0], device=device)
box_1 = torch.tensor([.0, 2., 2., 2., .0], device=device)
print(cal_iou(box_0[None, None, ...], box_1[None, None, ...])[0].cpu().numpy())

returns [[0.33333334]].
However, these 2 boxes are not intersecting.

compile error

can you help me?I meet some mistakes

cc1plus: warning: command line option ‘-Wstrict-prototypes’ is valid for C/ObjC but not for C++
In file included from sort_vert.cpp:1:0:
utils.h:27:64: warning: backslash-newline at end of file
#define CHECK_IS_BOOL(x)
^
sort_vert.cpp: In function ‘at::Tensor sort_vertices(at::Tensor, at::Tensor, at::Tensor)’:
utils.h:12:73: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_contiguous(), #x " must ne a contiguous tensor");
^
sort_vert.cpp:7:5: note: in expansion of macro ‘CHECK_CONTIGUOUS’
CHECK_CONTIGUOUS(vertices);
^
utils.h:12:73: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_contiguous(), #x " must ne a contiguous tensor");
^
sort_vert.cpp:8:5: note: in expansion of macro ‘CHECK_CONTIGUOUS’
CHECK_CONTIGUOUS(mask);
^
utils.h:12:73: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_contiguous(), #x " must ne a contiguous tensor");
^
sort_vert.cpp:9:5: note: in expansion of macro ‘CHECK_CONTIGUOUS’
CHECK_CONTIGUOUS(num_valid);
^
utils.h:7:61: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor");
^
sort_vert.cpp:10:5: note: in expansion of macro ‘CHECK_CUDA’
CHECK_CUDA(vertices);
^
utils.h:7:61: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor");
^
sort_vert.cpp:11:5: note: in expansion of macro ‘CHECK_CUDA’
CHECK_CUDA(mask);
^
utils.h:7:61: error: ‘TORCH_CHECK’ was not declared in this scope
TORCH_CHECK(x.is_cuda(), #x " must be a CUDA tensor");
^
sort_vert.cpp:12:5: note: in expansion of macro ‘CHECK_CUDA’
CHECK_CUDA(num_valid);
^
utils.h:24:49: error: ‘TORCH_CHECK’ was not declared in this scope
#x " must be a float tensor");
^
sort_vert.cpp:13:5: note: in expansion of macro ‘CHECK_IS_FLOAT’
CHECK_IS_FLOAT(vertices);
^
utils.h:30:48: error: ‘TORCH_CHECK’ was not declared in this scope
#x " must be a bool tensor");
^
sort_vert.cpp:14:5: note: in expansion of macro ‘CHECK_IS_BOOL’
CHECK_IS_BOOL(mask);
^
utils.h:18:47: error: ‘TORCH_CHECK’ was not declared in this scope
#x " must be a int tensor");
^
sort_vert.cpp:15:5: note: in expansion of macro ‘CHECK_IS_INT’
CHECK_IS_INT(num_valid);
^
sort_vert.cpp:23:54: error: expected primary-expression before ‘float’
sort_vertices_wrapper(b, n, m, vertices.data_ptr(), mask.data_ptr
^
sort_vert.cpp:23:78: error: expected primary-expression before ‘bool’
sort_vertices_wrapper(b, n, m, vertices.data_ptr(), mask.data_ptr(),
^
sort_vert.cpp:24:45: error: expected primary-expression before ‘int’
num_valid.data_ptr(), idx.data_ptr());
^
sort_vert.cpp:24:66: error: expected primary-expression before ‘int’
num_valid.data_ptr(), idx.data_ptr());
^
error: command 'gcc' failed with exit status 1

Sorting vertices is gives wrong result on different gpu

I have a 4 gpu server and I use the following code to test cal_iou function

    device = 'cuda:0'
    box3 = [-0.3541, -0.5818,  0.6220,  1.2440,  2.1768]
    box4 = [-0.4219, -0.1952,  0.3413,  0.6827,  0.8751]
    tensor1 = torch.FloatTensor(box3).to(device)[None,None] # 2, 4, 2 # test same box
    tensor2 = torch.FloatTensor(box4).to(device)[None,None]

    area = cal_iou(tensor1, tensor2)[0]

    print("CUDA: ")
    print(area)

When device is 'cuda:0' it seems to work fine, but when it is 'cuda:1' or 'cuda:2' or 'cuda:3', area gives 0 always. What is wrong?

loss suddenly increase?

Hi @lilanxiao,
thanks for your great work!
When I run the demo, I found that sometimes loss will suddenly increase and iou will suddenly drop.
Is there any ideas about this problem?
differentiableIOU_loss_problem

Please Help

请问一下大佬为啥执行完 python setup.py install后,会报错呢
Traceback (most recent call last):
File "setup.py", line 9, in
'sort_vert_kernel.cu',
File "/home/zhang/anaconda3/envs/RI/lib/python3.6/site-packages/torch/utils/cpp_extension.py", line 705, in CUDAExtension
library_dirs += library_paths(cuda=True)
File "/home/zhang/anaconda3/envs/RI/lib/python3.6/site-packages/torch/utils/cpp_extension.py", line 795, in library_paths
if (not os.path.exists(_join_cuda_home(lib_dir)) and
File "/home/zhang/anaconda3/envs/RI/lib/python3.6/site-packages/torch/utils/cpp_extension.py", line 1652, in _join_cuda_home
raise EnvironmentError('CUDA_HOME environment variable is not set. '
OSError: CUDA_HOME environment variable is not set. Please set it to your CUDA install root.

Bug with oriented_box_intersection_2d function

Hi, there, thanks for your excellent work.

There seems to have a bug in the oriented_box_intersection_2d function in box_intersection_2d.py. I found that results are different for the same input data when using different input orders or groups. Following is my test code.

import torch
import numpy as np

from box_intersection_2d import oriented_box_intersection_2d

device = torch.device("cuda:0")

# load 2 group of boxes, each group contains 9 boxes.
boxes1 = torch.from_numpy(np.load('boxes1.npy')).to(device)
boxes2 = torch.from_numpy(np.load('boxes2.npy')).to(device)

area, _ = oriented_box_intersection_2d(boxes1,boxes2)
print(area)

# calculate intersetion of boxes in the center 
box1 = boxes1[1,1].reshape(1,1,4,2)
box2 = boxes2[1,1].reshape(1,1,4,2)

area1, _ = oriented_box_intersection_2d(box1,box2)
print(area1)

# calculate intersetion of boxes in the center row
box_row1 = boxes1[1,:].reshape(3,1,4,2)
box_row2 = boxes2[1,:].reshape(3,1,4,2)

area_row, _ = oriented_box_intersection_2d(box_row1,box_row2)
print(area_row)

# calculate intersetion of boxes in the center column
box_col1 = boxes1[:,1].reshape(1,3,4,2)
box_col2 = boxes2[:,1].reshape(1,3,4,2)

area_col, _ = oriented_box_intersection_2d(box_col1,box_col2)
print(area_col)

The output of the code above is :

tensor([[1921.1929,  221.0000,    0.0000],
        [1246.7070, 1164.5000,    0.0000],
        [ 570.9585,   32.7373,    0.0000]], device='cuda:0')
tensor([[221.]], device='cuda:0')
tensor([[1246.7070],
        [1164.5000],
        [   0.0000]], device='cuda:0')
tensor([[221.0000, 221.0000,  32.7373]], device='cuda:0')

you can see the intersection result in the center position is different while calculating separately or together with other elements. And the correct result should be 221.0000, but the result is 1164.5 while calculating all the boxes together or only in the center row. Did I make a mistake anywhere? Thanks for your help.

boxes1.npy
boxes2.npy

CUDA编译出错

sort_vert.cpp第23行

sort_vertices_wrapper(b, n, m, vertices.data_ptr<float>(), mask.data_ptr<bool>(),
                     num_valid.data_ptr<int>(), idx.data_ptr<int>());

出现了错误:
sort_vert.cpp(23): error C2062: 意外的类型“float”

Yolact

Is it possible to apply this to YOLACT? How might i go about doing so?

ModuleNotFoundError: No module named 'sort_vertices' when run python demo

Please help to check what's wrong with the demo. thanks.

sudo /home/liey/anaconda3/envs/open-mmlab/bin/python setup.py install
running install
running bdist_egg
running egg_info
writing sort_vertices.egg-info/PKG-INFO
writing dependency_links to sort_vertices.egg-info/dependency_links.txt
writing top-level names to sort_vertices.egg-info/top_level.txt
reading manifest file 'sort_vertices.egg-info/SOURCES.txt'
writing manifest file 'sort_vertices.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_ext
creating build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-3.7/sort_vertices.cpython-37m-x86_64-linux-gnu.so -> build/bdist.linux-x86_64/egg
creating stub loader for sort_vertices.cpython-37m-x86_64-linux-gnu.so
byte-compiling build/bdist.linux-x86_64/egg/sort_vertices.py to sort_vertices.cpython-37.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying sort_vertices.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying sort_vertices.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying sort_vertices.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying sort_vertices.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
pycache.sort_vertices.cpython-37: module references file
creating 'dist/sort_vertices-0.0.0-py3.7-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing sort_vertices-0.0.0-py3.7-linux-x86_64.egg
removing '/home/liey/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/sort_vertices-0.0.0-py3.7-linux-x86_64.egg' (and everything under it)
creating /home/liey/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/sort_vertices-0.0.0-py3.7-linux-x86_64.egg
Extracting sort_vertices-0.0.0-py3.7-linux-x86_64.egg to /home/liey/anaconda3/envs/open-mmlab/lib/python3.7/site-packages
sort-vertices 0.0.0 is already the active version in easy-install.pth

Installed /home/liey/anaconda3/envs/open-mmlab/lib/python3.7/site-packages/sort_vertices-0.0.0-py3.7-linux-x86_64.egg
Processing dependencies for sort-vertices==0.0.0
Finished processing dependencies for sort-vertices==0.0.0

python demo.py
Traceback (most recent call last):
File "demo.py", line 25, in
from oriented_iou_loss import cal_diou, cal_giou
File "/home/liey/3D_multiview/mmdetection3d/mmdet3d/ops/rotated_iou/oriented_iou_loss.py", line 3, in
from box_intersection_2d import oriented_box_intersection_2d
File "/home/liey/3D_multiview/mmdetection3d/mmdet3d/ops/rotated_iou/box_intersection_2d.py", line 8, in
from cuda_op.cuda_ext import sort_v
File "/home/liey/3D_multiview/mmdetection3d/mmdet3d/ops/rotated_iou/cuda_op/cuda_ext.py", line 4, in
import sort_vertices
ModuleNotFoundError: No module named 'sort_vertices'

Ubuntu16.04
python3.7.2
torch:1.8.1

AttributeError: 'Tensor' object has no attribute 'square'

File "/home/a/code/box_iou_rotated_diff/min_enclosing_box.py", line 102, in point_line_distance_range
num = torch.sqrt((y2 - y1).square() + (x2 - x1).square() + 1e-14)
AttributeError: 'Tensor' object has no attribute 'square'

请教大佬代码实现问题

大佬您好,很感谢您的工作,我想将输入size(B , N, 5)修改为(B * N, 5),其他代码都能改,但是在cuda_op里面的不知道怎么改,例如cuda_ext.py中,我尝试修改v,m,nv的维度,将B , N修改成B*N,但是输出不对,所以想请问大佬这块如何修改喃,谢谢

Wrong IoU calculation when corners are smaller than 0

Hi! Thank you @lilanxiao for your great work. I have been using your work for sometime, and it has been beneficial for my training.

One problem I encountered was under certain circumstances, the IoU calculations are wrong. Most of them happened when the calculated corners of boxes are smaller than zero. Some happened when length or width are too small, which may have something to do with numeric instability. There's maybe other cases, but these two are what I have discovered.

My environment:
Ubuntu 18.04, CUDA 11.2, Pytorch 1.8, python 3.8

大佬,求助,CUDA out of memory

大佬,我用cal_iou求解旋转iou时候,进行广播机制,导致B和N就特别大,导致直接爆掉了,A100我降batchsize没用,有没有解决的办法喃。
image

Why are we sorting vertices to calculate 2D intersection?

I don't understand why we have to introduce the sort function to calculate the 2D intersection between oriented bounding boxes.
I have seen other implementations that can calculate it by looping through the two rectangles and finding the vertices that indicate a polygon intersection shape, then they just calculate the area of that shape using this formula:
image

https://github.com/maudzung/Complex-YOLOv4-Pytorch/blob/master/src/utils/cal_intersection_rotated_boxes.py#L42
https://developer.nvidia.com/blog/detecting-rotated-objects-using-the-odtk/

I'm just not sure why this sort() method is necessary.

Not able to run Rotated_IoU in Spyder but works in Anaconda Prompt

Hi,

I managed to run Rotated_IoU in the Anaconda Prompt by first running setup.py and then running demo.py.

I am not experienced with CUDAExtensions but when I try to run in spyder, i get the following error with setup.py:

DistutilsArgError: no commands supplied


During handling of the above exception, another exception occurred:

SystemExit: usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...]
   or: setup.py --help [cmd1 cmd2 ...]
   or: setup.py --help-commands
   or: setup.py cmd --help

error: no commands supplied

What are the required commands?

I am an R user that is trying to translate Rotated_IoU code into R. Can you explain why I can not get it to run in spyder?

Minimum Bounding Box implementation Rotating Calipers

The minimum bounding box method has three types (aligned, pca, and smallest). Is the "smallest" method using the "Rotating Calipers" algorithm? I was looking for a torch implementation of this and if this is it then thanks!

关于参数的疑问

您好!在cal_iou_3d函数中,参数形状是(B, N, 3+3+1), 请问这里的N是什么含义?非常感谢!

a problem when using 3d-giou for regression training

Hello,There is a problem when using 3d-giou for regression training. When I use 3d-giou to train 3dssd on my own dataset(5 classes: car perdestrian headstock fulltrailer emptytrailer), it seems that giou implementation extremely harmful for categories with large aspect ratio.(for example: when training the valid mAP for trailer is always 0, however the mAP for other types is normal and progressively increase. ) Additionally, it can be normally training using iou/ciou/diou for regression. Last, hope for your reply.Thanks~

Usage on KITTI

Hi, thanks for your great work.
I want to use these IoU losses on KITTI and evaluate the model performance. How should I do, and how to write the transform scrip?
Thanks in advance!

CUDA 11

Hi @lilanxiao ,
Looks like this code can't be compiled with cuda11. Can you please have a look at it?

Orientation Problems

Are you able to predict the correct orientation? I find cases where my predicted angles are not the same, OR that my width, height, length values are negative. See photo below:

In this case, the predicted corners may not be the same corner number as the ground truth. So width could be length etc

losses_giou_epoch_791_

sort_vert.cpp(23): error C2062: 意外的类型“float”

sort_vert.cpp第23行

sort_vertices_wrapper(b, n, m, vertices.data_ptr<float>(), mask.data_ptr<bool>(),
                     num_valid.data_ptr<int>(), idx.data_ptr<int>());

出现了错误:
sort_vert.cpp(23): error C2062: 意外的类型“float”

is this result correct?

import Rotated_IoU.oriented_iou_loss as ri
import torch
import numpy as np
import math
box1 = torch.tensor([[[0.,0.,2.,2.,torch.pi/4]]]).to("cuda")
iou,_,_,_ = ri.cal_iou(box1, box1)
print(iou)

above iou value is "0."

but when i change box angle torch.pi/4 to torch.pi/4 + 0.01, it return 1.0 and this is what i expected.

inf bbox loss when using cal_giou_3d ( but the iou is right)

Hi author,
Thank you for your nice work.
I encountered a case where I get bbox_iou of 0.7304, but bbox_loss: -inf.

After that it's:
CUDA kernel failed : invalid configuration argument.

Should I modify
giou_loss = 1. - iou3d + (v_c - u3d) / v_c
as
giou_loss = 1. - iou3d + (v_c - u3d) / (v_c + 1e-14)?

Thank you!

The computational cost of accurate rotated iou?

Thanks for your work.
I notice the computational cost of accurate rotated iou is very high. This code calculates and restores all the situations of intersection, so the GPU memory cost is also very high?

Batch computation for IoU Loss

Hello,

Thank you for your work. I have a question regarding the demo / the functionality of the cal_giou and cal_giou_3d functions.

It looks like from the demo the inputs must be the same size. that is, [Batch, Number of boxes, 7] for the 3D case.
However, if we have say 2 ground truth boxes in an image, and our model predicts 100 bounding boxes [B, 100,7], is there a way to compute the IoU between each of the boxes to the 2 ground truth boxes? [B,100,7] and [B,2,7] comparison.

--> meaning every predicted box from the 100 is compared to each of the 2 ground truth boxes. thus for any batch, there are 200 comparisons made

Thanks for your time

Box transformation

Thanks so much for the great code base. If my coordinate system is like the following, do you know how I should do the transformation? Thanks!

front: x
left: y
z: up
the definition of yaw is like:
y axis: -pi
y axis negative: 0
x axis: -pi/2

box_intersection_2d 中的box1_in_box2存在bug, box1_in_box2(box1,box1), 在特定数据下返回的不是[true,true,true,true]

我尝试在维基百科上查找了另外一种算法(叉积), 重写了此函数,是我对函数的理解有错误?或者你提供的原始的函数存在bug?
你有什么修正的建议吗?

  • 原始代码
def box1_in_box2(corners1:torch.Tensor, corners2:torch.Tensor):
    a = corners2[:, :, 0:1, :]  # (B, N, 1, 2)
    b = corners2[:, :, 1:2, :]  # (B, N, 1, 2)
    d = corners2[:, :, 3:4, :]  # (B, N, 1, 2)
    ab = b - a                  # (B, N, 1, 2)
    am = corners1 - a           # (B, N, 4, 2)
    ad = d - a                  # (B, N, 1, 2)
    p_ab = torch.sum(ab * am, dim=-1)       # (B, N, 4)
    norm_ab = torch.sum(ab * ab, dim=-1)    # (B, N, 1)
    p_ad = torch.sum(ad * am, dim=-1)       # (B, N, 4)
    norm_ad = torch.sum(ad * ad, dim=-1)    # (B, N, 1)
    # NOTE: the expression looks ugly but is stable if the two boxes are exactly the same
    # also stable with different scale of bboxes
    cond1 = (p_ab / norm_ab > - 1e-6) * (p_ab / norm_ab < 1 + 1e-6)   # (B, N, 4)
    cond2 = (p_ad / norm_ad > - 1e-6) * (p_ad / norm_ad < 1 + 1e-6)   # (B, N, 4)
    return cond1*cond2
  • 我修改后的代码
def box1_in_box2(corners1:torch.Tensor, corners2:torch.Tensor):
    p1 = corners2[:, :, 0:1, :]  # (B, N, 1, 2)
    p2 = corners2[:, :, 1:2, :]  # (B, N, 1, 2)
    p3 = corners2[:, :, 2:3, :]  # (B, N, 1, 2)
    p4 = corners2[:, :, 3:4, :]  # (B, N, 1, 2)
    p=corners1

    # p1 p2 * p3 p4 p
    x_in=\
        ((p2[...,0]-p1[...,0])*(p[...,1]-p1[...,1])-(p[...,0]-p1[...,0])*(p2[...,1]-p1[...,1])) * \
        ((p4[...,0]-p3[...,0])*(p[...,1]-p3[...,1])-(p[...,0]-p3[...,0])*(p4[...,1]-p3[...,1]))

    # p2 p3 * p4 p1 p
    y_in=\
        ((p3[...,0]-p2[...,0])*(p[...,1]-p2[...,1])-(p[...,0]-p2[...,0])*(p3[...,1]-p2[...,1])) * \
        ((p1[...,0]-p4[...,0])*(p[...,1]-p4[...,1])-(p[...,0]-p4[...,0])*(p1[...,1]-p4[...,1]))

    cond1= (x_in>=0)
    cond2= (y_in>=0)
    value= cond1*cond2
    return value

sort_v problem

hi,

i‘m interested in your Rotated_IoU, but my area calculation is wrong. When I check the code, sort_v function was wrong. Test as follows(the result of corners are not in order) :

  v = torch.zeros([1, 1, 24, 2]).float().cuda()
  v_1 = torch.Tensor([[330, 145], [270, 170], [250, 270], [320, 370], [430, 350], [470, 280], [460, 200], [415, 145]]).float().cuda()
  v[:, :, :len(v_1), :] = v_1
  mean = torch.mean(v, dim=2, keepdim=True)
  v = v - mean
  m = torch.zeros([1, 1, 24]).cuda()
  m[:, :, :len(v_1)] = 1
  m = m.bool()
  nv = torch.sum(m.int(), dim=-1).int().cuda()
  result = sort_v(v, m, nv)

A question about the code implementation

您好,看您的代码实现的时候,下面这一段代码的原理没有明白,能麻烦您解释一下这样写的原理吗

def box1_in_box2(corners1: torch.Tensor, corners2: torch.Tensor):
"""check if corners of box1 lie in box2

Args:
    corners1 (torch.Tensor): (B, N, 4, 2)
    corners2 (torch.Tensor): (B, N, 4, 2)

Returns:
    c1_in_2: (B, N, 4) Bool
"""
a = corners2[:, :, 0:1, :]  # (B, N, 1, 2)
b = corners2[:, :, 1:2, :]  # (B, N, 1, 2)
d = corners2[:, :, 3:4, :]  # (B, N, 1, 2)
ab = b - a  # (B, N, 1, 2) the length of w or h
am = corners1 - a  # (B, N, 4, 2)
ad = d - a  # (B, N, 1, 2) the length of w or h
p_ab = torch.sum(ab * am, dim=-1)  # (B, N, 4)
norm_ab = torch.sum(ab * ab, dim=-1)  # (B, N, 1)
p_ad = torch.sum(ad * am, dim=-1)  # (B, N, 4)
norm_ad = torch.sum(ad * ad, dim=-1)  # (B, N, 1)
cond1 = (p_ab > 0) * (p_ab < norm_ab)  # (B, N, 4)
cond2 = (p_ad > 0) * (p_ad < norm_ad)  # (B, N, 4)
return cond1 * cond2

backpropagation when Rotate_IOU = 0

Hi, @lilanxiao

I have question about backpropagation when rotate_IOU value is zero, a case when the number of vertices that intersect or inside another box are less than 3 .
How do you manage to backpropagate?

about backward function

hi, thanks for your work hocam

why backward function of SortVertices in cuda_ext.py does not have any calculations?
In this case, how gradients of the iou loss is calculated and backpropagation works?

Thank you

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.