Python 图像重叠分块 - Go语言中文社区

Python 图像重叠分块



import cv2
import math 
import numpy as np

from pathlib import Path

file_name = "121.tif"
save_path = './sunxu' # create dir sunxu
Path(save_path).mkdir(parents=True, exist_ok=True) 

# block size
height = 208
width = 208

# overlap 
over_x = 50
over_y = 50
h_val = height - over_x
w_val = width - over_y

# Set whether to discard an image that does not meet the size
mandatory = False

img = cv2.imread(file_name)

print(img.shape)
# original image size
original_height = img.shape[0]
original_width = img.shape[1]

max_row = float((original_height-height)/h_val)+1 
max_col = float((original_width-width)/w_val)+1

# block number
max_row = math.ceil(max_row) if mandatory == False else math.floor(max_row)
max_col = math.ceil(max_col) if mandatory == False else math.floor(max_col)

print(max_row)
print(max_col)

images = []
for i in range(max_row):
	images_temp = []
	for j in range(max_col):
		temp_path = save_path + '/' + str(i) + '_' + str(j) + '_'
		if ((width+j*w_val)>original_width and (i*h_val+height)<=original_height): # Judge the right most incomplete part
			temp = img[i*h_val:i*h_val+height,j*w_val:original_width,:]
			temp_path = temp_path + str(temp.shape[0]) + '_' + str(temp.shape[1]) + '.jpg'
			cv2.imwrite(temp_path,temp)
			images_temp.append(temp)
		elif ((height+i*h_val)>original_height and (j*w_val+width)<=original_width): # Judge the incomplete part at the bottom
			temp = img[i*h_val:original_height,j*w_val:j*w_val+width,:]
			temp_path = temp_path + str(temp.shape[0]) + '_' + str(temp.shape[1]) + '.jpg'
			cv2.imwrite(temp_path,temp)
			images_temp.append(temp)
		elif ((width+j*w_val)>original_width and (i*h_val+height)>original_height): # Judge the last slide
			temp = img[i*h_val:original_height,j*w_val:original_width,:]
			temp_path = temp_path + str(temp.shape[0]) + '_' + str(temp.shape[1]) + '.jpg'
			cv2.imwrite(temp_path,temp)
			images_temp.append(temp)
		else:
			temp = img[i*h_val:i*h_val+height,j*w_val:j*w_val+width,:]
			temp_path = temp_path + str(temp.shape[0]) + '_' + str(temp.shape[1]) + '.jpg'
			cv2.imwrite(temp_path,temp)
			images_temp.append(temp) # The rest of the complete
			
	images.append(images_temp)
		
print(len(images))

结果如下图:

参考的matlab地址为:http://blog.sciencenet.cn/blog-347785-931518.html

 

版权声明:本文来源CSDN,感谢博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/coolsunxu/article/details/102639674
站方申明:本站部分内容来自社区用户分享,若涉及侵权,请联系站方删除。
  • 发表于 2020-06-27 23:24:47
  • 阅读 ( 1358 )
  • 分类:

0 条评论

请先 登录 后评论

官方社群

GO教程

猜你喜欢