“Python-OpenCV” How to Split Image to Designated Number of Matrix

AI
higashi
higashi

Hi, I’m higashi.

 

This page introduces how to split image to designated number of matrix as shown below.

★Original Image

Sample image for split

★Split Image

Sample image of split picture

The sample is split to 6×6 images, but these number can change freely.

 

This is  likely useful to increase of teacher data for AI.

 

So, let’s get stared.

 

Sponsored Links

Check Folder Structure

The shown below is folder of sample program introduced later.

folder structure for sample code

★sample.ipg : Image to be Split

★split_pic.py : Program File Introduced Later

★split_pic : The Folder Split Images will be Saved

 

Sponsored Links

Sample Code of Split Image

The sample code is below.

 

In this case, image will split to 6×6.

It is designated by variables ‘split_x’ and ‘split_y’.

#library import
import cv2
import numpy as np
#load image
img=cv2.imread('sample.jpg',cv2.IMREAD_COLOR)
h,w=img.shape[:2]
#split number of horizontal and vertical
split_x=6
split_y=6
#image split process
cx=0
cy=0
for j in range(split_x):
    for i in range(split_y):
        split_pic=img[cy:cy+int(h/split_y),cx:cx+int(w/split_x),:]
        cv2.imwrite('split_pic/split_y'+str(i)+'_x'+str(j)+'.jpg',split_pic)
        cy=cy+int(h/split_y)
    cy=0
    cx=cx+int(w/split_x)

 

Sponsored Links

Execution Result of Sample Code

Finally, let’s conduct the sample code introduced earlier.

 

★The result of ‘split_x=6’ and ‘split_y=6’.

The Result split 6 by 6

★The result of ‘split_x=4’ and ‘split_y=4’.

The Result split 4 by 4

I think it is likely running fine.

 

That’s all. Thank you!!

コメント