Megid
Megid

Reputation: 105

Fill image up to a size with Python

I am writing a handwriting recognition app and my inputs have to be of a certain size (128x128). When I detect a letter it looks like this:

this

That image for instance has a size of 40x53. I want to make it 128x128, but simply resizing it lowers the quality especially for smaller images. I want to somehow fill the rest up to 128x128 with the 40x53 in the middle. The background color should also stay relatively the same. I am using Python's opencv but I am new to it. How can I do this, and is it even possible?

Upvotes: 0

Views: 2188

Answers (2)

Ishara Dayarathna
Ishara Dayarathna

Reputation: 3601

Here you can get what you have asked using outputImage. Basically I have added a border using copyMakeBorder method. You can refer this for more details. You have to set the color value as you want in the value parameter. For now it is white [255,255,255].

But I would rather suggest you to resize the original image, seems like it is the better option than what you have asked. Get the image resized you can use resized in the following code. For your convenience I have added both methods in this code.

import cv2
import numpy as np
inputImage = cv2.imread('input.jpg', 1)

outputImage = cv2.copyMakeBorder(inputImage,37,38,44,44,cv2.BORDER_CONSTANT,value=[255,255,255])

resized = cv2.resize(inputImage, (128,128), interpolation = cv2.INTER_AREA)
cv2.imwrite('output.jpg', outputImage)
cv2.imwrite('resized.jpg', resized)

Upvotes: 1

Wool
Wool

Reputation: 138

I believe you want to scale your image.

This code might help:

import cv2

img = cv2.imread('name_of_image', cv2.IMREAD_UNCHANGED)

# Get original size of image
print('Original Dimensions: ',img.shape)

# Percentage of the original size
scale_percent = 220

width = int(img.shape[1] * scale_percent / 100)
height = int(img.shape[0] * scale_percent / 100)
dim = (width, height)

# Resize/Scale the image
resized = cv2.resize(img, dim, interpolation = cv2.INTER_AREA)

# The new size of the image
print('Resized Dimensions: ',resized.shape)

cv2.imshow("Resized image", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()

Upvotes: 1

Related Questions