I have very large images 10k by 10k that i need to split into overlapping boxes as shown below. Id like the box to be of size X by Y and I need to stride(distance the box moves across the image in pixels) that box across the screen a given distance. Then Save each individual box section as its own image file. Id like to be able to change the X and Y values and the stride value. I'm using Python and have OpenCV Thank you.
Asked
Active
Viewed 4,370 times
0
-
2What have you tried so far? Show your efforts – Raj Dec 16 '19 at 04:53
-
Search for numpy slicing on Google or this forum to crop one tile. You will likely have to write a loop over your image for each tile you want doing your own computations of the offsets for the top left corner along with your fixed width and height values. See for example the answer at https://stackoverflow.com/questions/15589517/how-to-crop-an-image-in-opencv-using-python using `crop_img = img[y:y+h, x:x+w]` Then write that tile to disk – fmw42 Dec 16 '19 at 06:25
1 Answers
2
Here is function, that splits image with overlapping from all sides. On the borders it will be filled with zeros.
What it essentially does: it creates a bigger image with zero padding, and then extract patches of size window_size+2*margin
with strides of window_size
.
(You may want to adjust it to your needs)
def split(img, window_size, margin):
sh = list(img.shape)
sh[0], sh[1] = sh[0] + margin * 2, sh[1] + margin * 2
img_ = np.zeros(shape=sh)
img_[margin:-margin, margin:-margin] = img
stride = window_size
step = window_size + 2 * margin
nrows, ncols = img.shape[0] // window_size, img.shape[1] // window_size
splitted = []
for i in range(nrows):
for j in range(ncols):
h_start = j*stride
v_start = i*stride
cropped = img_[v_start:v_start+step, h_start:h_start+step]
splitted.append(cropped)
return splitted
Running this
img = np.arange(16).reshape(4,4)
out = split(img, window_size=2, margin=1)
will return
[array([[ 0., 0., 0., 0.],
[ 0., 0., 1., 2.],
[ 0., 4., 5., 6.],
[ 0., 8., 9., 10.]]),
array([[ 0., 0., 0., 0.],
[ 1., 2., 3., 0.],
[ 5., 6., 7., 0.],
[ 9., 10., 11., 0.]]),
array([[ 0., 4., 5., 6.],
[ 0., 8., 9., 10.],
[ 0., 12., 13., 14.],
[ 0., 0., 0., 0.]]),
array([[ 5., 6., 7., 0.],
[ 9., 10., 11., 0.],
[13., 14., 15., 0.],
[ 0., 0., 0., 0.]])]

Vadym B.
- 681
- 7
- 21