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

Crop coords can be outside of image #166

Open
DirtyRacer1337 opened this issue Feb 12, 2022 · 2 comments · May be fixed by #171
Open

Crop coords can be outside of image #166

DirtyRacer1337 opened this issue Feb 12, 2022 · 2 comments · May be fixed by #171
Labels

Comments

@DirtyRacer1337
Copy link

I've noticed that sometimes image can be outside of source image, code below, you can test it. I've also make some quick fixes, I hope you know how to do it better

data = [
    (663, 2495, 185, 867, 327, 354),
    (612, 1020, 13, 280, 26, 33),
    (612, 1020, 979, 282, 24, 34),
    (612, 1020, 1003, 169, 16, 21),
    (612, 1020, 993, 351, 26, 44),
    (612, 1020, 996, 271, 21, 26),
    (612, 1020, 9, 382, 30, 49),
    (612, 1020, 0, 231, 14, 27),
]

crop = Cropper()
for item in data:
    pos = crop.crop_positions(*item)
    print(*item)
    print(pos)
    print('---')

Output:

663 2495 185 867 327 354
[690, 1398, -5, 702]
---
612 1020 13 280 26 33
[263, 329, -7, 59]
---
612 1020 979 282 24 34
[265, 333, 957, 1025]
---
612 1020 1003 169 16 21
[167, 191, 999, 1022]
---
612 1020 993 351 26 44
[349, 396, 982, 1029]
---
612 1020 996 271 21 26
[267, 300, 989, 1023]
---
612 1020 9 382 30 49
[367, 445, -15, 63]
---
612 1020 0 231 14 27
[231, 258, -6, 20]
---

Fixes:

  1. Try to save aspect ratio
def _crop_positions(self, imgh, imgw, x, y, w, h):
    if h1 < 0:
        h1, h2 = 0, h2 + abs(h1)
    if v1 < 0:
        v1, v2 = 0, v2 + abs(v1)
    if h2 > imgw:
        h1, h2 = h1 + abs(h2 - imgw), imgw
    if v2 > imgh:
        v1, v2 = v1 + abs(v2 - imgh), imgh
  1. Just crop and lose aspect ratio
def _crop_positions(self, imgh, imgw, x, y, w, h):
    pos = self._clamp(v1, 0, imgh), self._clamp(v2, 0, imgh), self._clamp(h1, 0, imgw), self._clamp(h2, 0, imgw)

@staticmethod
def _clamp(n: int, min_n: int, max_n: int):
    return max(min(max_n, n), min_n)
@leblancfg leblancfg added the bug label Mar 1, 2022
@leblancfg
Copy link
Owner

I was meaning to release another patch version shortly, but I'll fix this and include it – bump to minor version instead.

@DirtyRacer1337
Copy link
Author

ok, hope you will find better solution and just for the note, coordinates can be also bigger than image, not negative only

612 1020 993 351 26 44
[349, 396, 982, 1029]

612 1020 996 271 21 26
[267, 300, 989, 1023]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants