本文主要介绍了python 边缘扩充方式的实现示例,具体如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
import cv2 # big_pad=True:当目标图像高和宽均大于原图时,进行边缘填充 # big_pad=False:按照目标尺寸的最小缩放比例,先缩放,再进行边缘填充 # borderType=cv2.BORDER_CONSTANT:表示常量填充,borderValue为填充常量0~255(黑~白) # borderType=cv2.BORDER_REPLICATE:边界复制填充 # borderType=cv2.BORDER_REFLECT:边界反射填充 # borderType=cv2.BORDER_WRAP:边框包装填充 def image_padding(image, target_shape, big_pad = True , borderType = cv2.BORDER_REFLECT, borderValue = ( 0 , 0 , 0 )): # 目标尺寸大小 ph, pw = target_shape # 原始图片尺寸 h, w, _ = image.shape if big_pad and ph > h and pw > w: # 以原图为中心进行边缘填充 top = bottom = (ph - h) / / 2 # 获取上、下填充尺寸 top + = (ph - h) % 2 # 为保证目标大小,无法整除则上+1 left = right = (pw - w) / / 2 left + = (pw - w) % 2 # 为保证目标大小,同理左上+1 image_padded = cv2.copyMakeBorder(image, top, bottom, left, right, borderType = borderType, value = borderValue) else : # 最小比例缩放填充(大尺寸:高/宽比例变化较大的将被填充,小尺寸反之) # 计算缩放后图片尺寸 scale = min (pw / w, ph / h) # 获取高/宽变化最小比例 nw, nh = int (scale * w), int (scale * h) # 对原图按照目标尺寸的最小比例进行缩放 img_resized = cv2.resize(image, (nw, nh)) top = bottom = (ph - nh) / / 2 # 获取上、下填充尺寸 top + = (ph - nh) % 2 # 为保证目标大小,无法整除则上+1 left = right = (pw - nw) / / 2 left + = (pw - nw) % 2 # 为保证目标大小,同理左上+1 image_padded = cv2.copyMakeBorder(img_resized, top, bottom, left, right, borderType = borderType, value = borderValue) return image_padded if __name__ = = "__main__" : path = './2_2.png' img = cv2.imread(path) img_pad = image_padding(img, ( 640 , 640 )) cv2.imwrite( './1_BORDER_WRAP.png' ,img_pad) # cv2.imwrite('./1_.png',img_pad[64:576,64:576]) |
原图
BORDER_WRAP
REFLECT
到此这篇关于python 边缘扩充方式的实现示例的文章就介绍到这了,更多相关python 边缘扩充 内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_20373723/article/details/123142344