Image Resize, Image Padding, Image Scanning
Python
OpenCV
Image Resizing
Image Cropping
Target Size
Conditions
Processing
This Python code uses OpenCV to resize and crop images according to specified conditions, ultimately processing them into smaller versions.
def scanImageWithWindowSizeAutoResize(
image,
width,
height,=False,
return_direction=0.1, # minimum 'fresh' area left for scanning
threshold# shall you use torch? no?
): = image.shape
shape assert len(shape) == 3
= shape
ih, iw, channels = max(width, math.floor(iw * height / ih))
targetWidth = max(height, math.floor(ih * width / iw))
targetHeight = cv2.resize(
resized =cv2.INTER_CUBIC
image, (targetWidth, targetHeight), interpolation
)# determine scan direction here.
= []
imageSeries if targetWidth / targetHeight == width / height:
= [resized] # as image series.
imageSeries = None
direction elif targetWidth / targetHeight < width / height:
= "vertical"
direction # the scanning is along the vertical axis, which is the height.
= 0
index while True:
= height * index, height * (index + 1)
start, end if start < targetHeight:
if end > targetHeight:
if 1 - (end - targetHeight) / targetHeight >= threshold:
= targetHeight
end = targetHeight - height
start else:
break
# other conditions, just fine
else:
break # must exit since nothing to scan.
= resized[start:end, :, :] # height, width, channels
cropped
imageSeries.append(cropped)+= 1
index else:
= "horizontal"
direction = 0
index while True:
= width * index, width * (index + 1)
start, end if start < targetWidth:
if end > targetWidth:
if 1 - (end - targetWidth) / targetWidth >= threshold:
= targetWidth
end = targetWidth - width
start else:
break
# other conditions, just fine
else:
break # must exit since nothing to scan.
= resized[:, start:end, :] # height, width, channels
cropped
imageSeries.append(cropped)+= 1
index if return_direction:
return imageSeries, direction
else:
return imageSeries
def resizeImageWithPadding(
image,
width,
height,"constant_black", "replicate"] = "constant_black",
border_type: Literal[
):= image.shape
shape assert len(shape) == 3
= shape
ih, iw, channels = min(width, math.floor(iw * height / ih))
targetWidth = min(height, math.floor(ih * width / iw))
targetHeight = cv2.resize(
resized =cv2.INTER_CUBIC
image, (targetWidth, targetHeight), interpolation
)= [0] * channels
BLACK = max(0, math.floor((height - targetHeight) / 2))
top = max(0, height - targetHeight - top)
bottom = max(0, math.floor((width - targetWidth) / 2))
left = max(0, width - targetWidth - left)
right if border_type == "constant_black":
= cv2.copyMakeBorder(
padded =BLACK
resized, top, bottom, left, right, cv2.BORDER_CONSTANT, value
)elif border_type == "replicate":
= cv2.copyMakeBorder(
padded =BLACK
resized, top, bottom, left, right, cv2.BORDER_REPLICATE, value
)else:
raise Exception("unknown border_type: %s" % border_type)
return padded