background
Students who are engaged in the application of remote sensing in deep learning will encounter the cutting of a large range of remote sensing images into regular and small range images in sequence. Since I’ve done this before, I’ll share how I crop a large grid image regularly.
Cutting method
QGIS cutting
We have a Google image of Beijing and want to crop it to 256256 size slices.Select our image, Export, Save as:Select VRT and select the size of the cut image, for example, the size of each image we get is 256256: The output will give us the result we need.
Python tailored
I forgot to back up the code I wrote when I was a student, so I sorted out the tailored code on the Internet. The principle is the same, and the libraries used are different, some use OpencV, some use PIL:
Clipping code one
from cv2 import cv2
import numpy as np
Img_To_Clip = '.jpg' # Position of the segmented image
pic_target = '/result/' # The folder to save the segmented images
# The size to be split
cut_width = 512
cut_length = 512
Read the image to be segmented, and its size and other data
picture = cv2.imread(Img_To_Clip)
(width, length, depth) = picture.shape
# Preprocess to generate 0 matrix
pic = np.zeros((cut_width, cut_length, depth))
# Count the number of horizontal and vertical partitions
num_width = int(width / cut_width)
num_length = int(length / cut_length)
# for loop generates iteratively
for i in range(0, num_width):
for j in range(0, num_length):
pic = picture[i*cut_width : (i+1)*cut_width, j*cut_length : (j+1)*cut_length, :]
result_path = pic_target + '{}_{}.jpg'.format(i+1, j+1)
cv2.imwrite(result_path, pic)
Copy the code
Clipping code two
from cv2 import cv2
# read file
im=cv2.imread(Img_To_Clip)
Get the number of rows and columns of the small slice
M = im.shape[0] / /2
N = im.shape[1] / /2
# cutting
tiles = [im[x:x+M,y:y+N] for x in range(0,im.shape[0],M) for y in range(0,im.shape[1],N)]
Copy the code
Clipping Code three
from PIL import Image
def crop(path, input, height, width, k, page, area) :
im = Image.open(input)
imgwidth, imgheight = im.size
for i in range(0,imgheight,height):
for j in range(0,imgwidth,width):
box = (j, i, j+width, i+height)
a = im.crop(box)
try:
o = a.crop(area)
o.save(os.path.join(path,"PNG"."%s" % page,"IMG-%s.png" % k))
except:
pass
k +=1
Copy the code
Reference: stackoverflow.stackoverflow.com/questions/5… CSDN.blog.csdn.net/qq_40608730… Stackoverflow.stackoverflow.com/questions/3…