Skip to content

Commit 4ba82a0

Browse files
authored
Merge pull request #18 from edgeimpulse/fix-image-rescale
Correct calculation for crop
2 parents 8a48b54 + 2496d9c commit 4ba82a0

File tree

1 file changed

+7
-6
lines changed

1 file changed

+7
-6
lines changed

edge_impulse_linux/image.py

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -82,20 +82,22 @@ def get_features_from_image(self, img, crop_direction_x='center', crop_direction
8282
factor_w = EI_CLASSIFIER_INPUT_WIDTH / in_frame_cols
8383
factor_h = EI_CLASSIFIER_INPUT_HEIGHT / in_frame_rows
8484

85+
# Maintain the same aspect ratio by scaling by the same factor for both dimensions
8586
largest_factor = factor_w if factor_w > factor_h else factor_h
8687

8788
resize_size_w = int(math.ceil(largest_factor * in_frame_cols))
8889
resize_size_h = int(math.ceil(largest_factor * in_frame_rows))
90+
# One dim will match the classifier size, the other will be larger
8991
resize_size = (resize_size_w, resize_size_h)
9092

91-
resized = cv2.resize(img, resize_size, interpolation = cv2.INTER_AREA)
93+
resized = cv2.resize(img, resize_size, interpolation=cv2.INTER_AREA)
9294

9395
if (crop_direction_x == 'center'):
94-
crop_x = int((resize_size_w - resize_size_h) / 2) if resize_size_w > resize_size_h else 0
96+
crop_x = int((resize_size_w - EI_CLASSIFIER_INPUT_WIDTH) / 2) # 0 when same
9597
elif (crop_direction_x == 'left'):
9698
crop_x = 0
9799
elif (crop_direction_x == 'right'):
98-
crop_x = resize_size_w - EI_CLASSIFIER_INPUT_WIDTH
100+
crop_x = resize_size_w - EI_CLASSIFIER_INPUT_WIDTH # can't be negative b/c one size will match input and the other will be larger
99101
else:
100102
raise Exception('Invalid value for crop_direction_x, should be center, left or right')
101103

@@ -108,9 +110,8 @@ def get_features_from_image(self, img, crop_direction_x='center', crop_direction
108110
else:
109111
raise Exception('Invalid value for crop_direction_y, should be center, top or bottom')
110112

111-
crop_region = (crop_x, crop_y, EI_CLASSIFIER_INPUT_WIDTH, EI_CLASSIFIER_INPUT_HEIGHT)
112-
113-
cropped = resized[crop_region[1]:crop_region[1]+crop_region[3], crop_region[0]:crop_region[0]+crop_region[2]]
113+
cropped = resized[crop_y: crop_y + EI_CLASSIFIER_INPUT_HEIGHT,
114+
crop_x: crop_x + EI_CLASSIFIER_INPUT_WIDTH]
114115

115116
if self.isGrayscale:
116117
cropped = cv2.cvtColor(cropped, cv2.COLOR_BGR2GRAY)

0 commit comments

Comments
 (0)