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

 

  • 3
    点赞
  • 24
    收藏
    觉得还不错? 一键收藏
  • 14
    评论
评论 14
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值