Last active
April 25, 2021 06:26
-
-
Save magesh-technovator/87d2fede639c332bec8dee18e4cb2f87 to your computer and use it in GitHub Desktop.
Image pre-processing for CRAFT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
from skimage import io | |
import cv2 | |
def loadImage(img_file): | |
img = io.imread(img_file) # RGB order | |
if img.shape[0] == 2: img = img[0] | |
if len(img.shape) == 2 : img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB) | |
if img.shape[2] == 4: img = img[:,:,:3] | |
img = np.array(img) | |
return img | |
def normalizeMeanVariance(in_img, mean=(0.485, 0.456, 0.406), variance=(0.229, 0.224, 0.225)): | |
# should be RGB order | |
img = in_img.copy().astype(np.float32) | |
img -= np.array([mean[0] * 255.0, mean[1] * 255.0, mean[2] * 255.0], dtype=np.float32) | |
img /= np.array([variance[0] * 255.0, variance[1] * 255.0, variance[2] * 255.0], dtype=np.float32) | |
return img | |
def resize_aspect_ratio(img, square_size, interpolation, mag_ratio=1): | |
height, width, channel = img.shape | |
# magnify image size | |
target_size = mag_ratio * max(height, width) | |
# set original image size | |
if target_size > square_size: | |
target_size = square_size | |
ratio = target_size / max(height, width) | |
target_h, target_w = int(height * ratio), int(width * ratio) | |
proc = cv2.resize(img, (target_w, target_h), interpolation = interpolation) | |
# make canvas and paste image | |
target_h32, target_w32 = target_h, target_w | |
if target_h % 32 != 0: | |
target_h32 = target_h + (32 - target_h % 32) | |
if target_w % 32 != 0: | |
target_w32 = target_w + (32 - target_w % 32) | |
resized = np.zeros((target_h32, target_w32, channel), dtype=np.float32) | |
resized[0:target_h, 0:target_w, :] = proc | |
target_h, target_w = target_h32, target_w32 | |
size_heatmap = (int(target_w/2), int(target_h/2)) | |
return resized, ratio, size_heatmap | |
# Load the image | |
image = imgproc.loadImage(image_path) | |
# Resize the image | |
img_resized, target_ratio, size_heatmap = resize_aspect_ratio(image, args.canvas_size, interpolation=cv2.INTER_LINEAR, mag_ratio=args.mag_ratio) | |
ratio_h = ratio_w = 1 / target_ratio | |
# Normalize the image | |
x = normalizeMeanVariance(img_resized) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment