'Resizing image without distortion creates a square background but in black
In order to maintain the aspect ratio of my image I'm making use of the following code to create a square block and applying my image over this which is fine but the problem is the leftover background is dark/black is there a way to keep that white/transparent?
my code:
def resize_image(img, size=(28,28)):
h, w = img.shape[:2]
c = img.shape[2] if len(img.shape)>2 else 1
if h == w:
return cv2.resize(img, size, cv2.INTER_AREA)
dif = h if h > w else w
interpolation = cv2.INTER_AREA if dif > (size[0]+size[1])//2 else
cv2.INTER_CUBIC
x_pos = (dif - w)//2
y_pos = (dif - h)//2
if len(img.shape) == 2:
mask = np.zeros((dif, dif), dtype=img.dtype)
mask[y_pos:y_pos+h, x_pos:x_pos+w] = img[:h, :w]
else:
mask = np.zeros((dif, dif, c), dtype=img.dtype)
mask[y_pos:y_pos+h, x_pos:x_pos+w, :] = img[:h, :w, :]
return cv2.resize(mask, size, interpolation)
Solution 1:[1]
The background color is the color you initialize it with. (mask = np.zeros...)
To have a white background use np.ones and for a specific color add a line after initialization mask[:, :] = (255, 0, 0).
Solution 2:[2]
You need to modify the mask you are using. It is initialized with zeros making the background black.
In the following snippet I have inverted the mask using cv2.bitwise_not() and used the result as background.
def resize_image1(img, size=(28,28)):
h, w = img.shape[:2]
c = img.shape[2] if len(img.shape)>2 else 1
if h == w:
return cv2.resize(img, size, cv2.INTER_AREA)
dif = h if h > w else w
interpolation = cv2.INTER_AREA if dif > (size[0]+size[1])//2 else cv2.INTER_CUBIC
x_pos = (dif - w)//2
y_pos = (dif - h)//2
if len(img.shape) == 2:
mask = np.ones((dif, dif), dtype=img.dtype)
mask = cv2.bitwise_not(mask) # Added mask inversion here
mask[y_pos:y_pos+h, x_pos:x_pos+w] = img[:h, :w]
else:
mask = np.ones((dif, dif, c), dtype=img.dtype)
mask = cv2.bitwise_not(mask) # Added mask inversion here
mask[y_pos:y_pos+h, x_pos:x_pos+w, :] = img[:h, :w, :]
return cv2.resize(mask, size, interpolation)
Sample output of image resized to 150 x 150 dimensions:
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | terrafox |
| Solution 2 |


