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

[Dy2St] transforms.RandomCrop Support static mode #49057

Merged
merged 3 commits into from
Dec 16, 2022
Merged
Show file tree
Hide file tree
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
44 changes: 44 additions & 0 deletions python/paddle/tests/test_transforms_static.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ def static_transform(self):

def test_transform(self):
dy_res = self.dynamic_transform()
if isinstance(dy_res, paddle.Tensor):
dy_res = dy_res.numpy()
st_res = self.static_transform()

np.testing.assert_almost_equal(dy_res, st_res)
Expand Down Expand Up @@ -98,5 +100,47 @@ def set_trans_api(self):
self.api = transforms.RandomVerticalFlip(prob=1)


class TestRandomCrop_random(TestTransformUnitTestBase):
def get_shape(self):
return (3, 240, 240)

def set_trans_api(self):
self.crop_size = (224, 224)
self.api = transforms.RandomCrop(self.crop_size)

def assert_test_random_equal(self, res, eps=10e-5):

_, h, w = self.get_shape()
c_h, c_w = self.crop_size
res_assert = True
for y in range(h - c_h):
for x in range(w - c_w):
diff_abs_sum = np.abs(
(self.img[:, y : y + c_h, x : x + c_w] - res)
).sum()
if diff_abs_sum < eps:
res_assert = False
break
if not res_assert:
break
assert not res_assert

def test_transform(self):
dy_res = self.dynamic_transform().numpy()
st_res = self.static_transform()

self.assert_test_random_equal(dy_res)
self.assert_test_random_equal(st_res)


class TestRandomCrop_same(TestTransformUnitTestBase):
def get_shape(self):
return (3, 224, 224)

def set_trans_api(self):
self.crop_size = (224, 224)
self.api = transforms.RandomCrop(self.crop_size)


if __name__ == "__main__":
unittest.main()
8 changes: 6 additions & 2 deletions python/paddle/vision/transforms/transforms.py
Original file line number Diff line number Diff line change
Expand Up @@ -1138,8 +1138,12 @@ def _get_param(self, img, output_size):
if w == tw and h == th:
return 0, 0, h, w

i = random.randint(0, h - th)
j = random.randint(0, w - tw)
if paddle.in_dynamic_mode():
i = random.randint(0, h - th)
j = random.randint(0, w - tw)
else:
i = paddle.randint(low=0, high=h - th)
j = paddle.randint(low=0, high=w - tw)
return i, j, th, tw

def _apply_image(self, img):
Expand Down