Reputation: 2965
I am trying to resize the input image to 736 x 736 as output size preserving the aspect ratio of the original image and add zero paddings while doing so.
The function image_resize_add_padding()
works fine and is doing what I am trying to do. The resized image looks good while displaying using cv2.imshow()
function
but while saving using cv2.imwrite()
function it seems to be a fully black image.
How do I save the correct image as it was displayed?
import cv2
import numpy as np
def image_resize_add_padding(image, target_size):
ih, iw = target_size
h, w, _ = image.shape
scale = min(iw/w, ih/h)
nw, nh = int(scale * w), int(scale * h)
image_resized = cv2.resize(image, (nw, nh))
image_paded = np.full(shape=[ih, iw, 3], fill_value=128.0)
dw, dh = (iw - nw) // 2, (ih-nh) // 2
image_paded[dh:nh+dh, dw:nw+dw, :] = image_resized
image_paded = image_paded / 255.
return image_paded
input_size = 736
image_path = "test_image.jpg"
original_image = cv2.imread(image_path)
output_image = image_resize_add_padding(
np.copy(original_image), [input_size, input_size])
cv2.imshow('image', output_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('test_output.jpg', output_image)
Upvotes: 2
Views: 847
Reputation: 96
The imshow function and imwrite using the JPG format handle floating-point image buffers differently.
The line where you divided the image by 255.
changed the image format to floating point. For the image data to be handled properly by the JPG writer, you can, for example, convert your buffer to uint8 (and make sure the values are in the range 0-255) before calling imwrite.
edit:
The code converts the image to floating point and also changes the range to 0-1. It is unclear why this is done, but if you want to keep the function as is, you can prepare the image for the imwrite
call like this:
output_image = (output_image * 255).astype('uint8')
Upvotes: 3