简单的图像加宽和截取类

支持图像加宽高,或截掉宽高

Posted by yaohong on Monday, October 26, 2020

TOC

简单的图像加宽和截取类

源码如下:

class ImageUtils:

	def __init__(self):
		import numpy;
		self.np = numpy;
		pass

	## 
	def resizePadding(self, np_2d_image, target_width,target_height):
		single_img 		= np_2d_image;
		tmp_img_width 	= single_img.shape[1]
		tmp_img_height 	= single_img.shape[0]
		np 				= self.np
		print("resizeFile origin shape :",single_img.shape)
		# 宽度pading添加
		if tmp_img_width < target_width:
			for x in range(tmp_img_width, target_width):
				# tmp_arr    = np.arange(255,255,(len(single_img),1));
				if x%2 == 0:
					single_img = np.insert(single_img, 0, 255,axis=1);
				else:
					single_img = np.insert(single_img, single_img.shape[1], 255,axis=1);
				# print(file_name_prefix, "origin shape :",single_img.shape)
		# 高度pading添加
		if tmp_img_height < target_height:
			for x in range(tmp_img_height, target_height):
				# tmp_arr    = np.arange(255,255,(len(single_img),1));
				if x%2 == 0:
					single_img = np.insert(single_img, 0, 255,axis=0);
				else:
					single_img = np.insert(single_img, single_img.shape[0], 255,axis=0);

		# 宽度截掉
		if tmp_img_width > target_width:
			for x in range(target_width, tmp_img_width):
				if x%2 == 0:
					single_img = np.delete(single_img, 0, axis=1);
				else:
					single_img = np.delete(single_img, single_img.shape[1]-1, axis=1);

		# 高度截掉
		if tmp_img_height > target_height:
			for x in range(target_height, tmp_img_height):
				if x%2 == 0:
					single_img = np.delete(single_img, 0, axis=0);
				else:
					single_img = np.delete(single_img, single_img.shape[0]-1, axis=0);


		print("resizeFile after shape :",single_img.shape)
		return single_img;

调用代码

import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import numpy as np

import pathlib
current_file_path = pathlib.Path(__file__).parent.absolute()
path_to_name 		= str(current_file_path) + "/liter_img_1603711717_0.jpeg"
orig_img 			= mpimg.imread(path_to_name) 

plt.imshow(orig_img)
plt.show();

#原图大小
print("orig_img",orig_img.shape) # output: orig_img (20, 14)

imgUtils 		= ImageUtils()

padding_resize_width 	= 20;#宽度加宽 
padding_resize_height 	= 20;
orig_img 			= imgUtils.resizePadding(orig_img,padding_resize_width,padding_resize_height);

# padding_resize_width 	= 5; # 宽度缩小 
# padding_resize_height 	= 20;
# orig_img 			= imgUtils.resizePadding(orig_img,padding_resize_width,padding_resize_height);


# padding_resize_width 	= 14;
# padding_resize_height 	= 40; # 高度增加
# orig_img 			= imgUtils.resizePadding(orig_img,padding_resize_width,padding_resize_height);


# padding_resize_width 	= 14;
# padding_resize_height 	= 5; # 高度缩小
# orig_img 			= imgUtils.resizePadding(orig_img,padding_resize_width,padding_resize_height);


plt.imshow(orig_img)
plt.show();

「点个赞」

Yaohong

点个赞

使用微信扫描二维码完成支付