Home > database >  cv2 Splitting image into multiple files with unique filenames
cv2 Splitting image into multiple files with unique filenames

Time:07-11

I'm applying a matplotlib to an image with custom x,y axis positional labels, and I'm wanting to use cv2 (or other) to split the image into seperate files with the filename being that of the label. I'd like to split from the bottom-left working outward, much like the label naming I've applied.

A sample image with labels:

sunset_labels

The logic behind my grid labels:

# Grid defn
myInterval=128
loc = plticker.MultipleLocator(base=myInterval)
xloc = plticker.MultipleLocator(base=myInterval)
ax.xaxis.set_major_locator(xloc)
ax.yaxis.set_major_locator(loc)
ax.xaxis.set_major_formatter(plticker.NullFormatter())
ax.yaxis.set_major_formatter(plticker.NullFormatter())
ax.tick_params(bottom=False, left=False)

# Add the grid
width, height = image.size
ax.grid(visible=True, axis='both', linestyle='-', linewidth=0.1)
ax.set(xlim=(0,width), ylim=(0,height))

# Find number of gridsquares in x and y direction
nx=abs(int((ax.get_xlim()[1]-ax.get_xlim()[0])/myInterval))
ny=abs(int((ax.get_ylim()[1]-ax.get_ylim()[0])/myInterval))

# Add coordinates
for j in range(ny):
    y=myInterval/2 j*myInterval
    for i in range(nx):
        x=myInterval/2 i*myInterval
        ax.text(x-20,y-41,f'{i 18}_{j 39}', color='w', fontsize=3, ha='right', va='top') # Offset  18

How would I split the image in such a way, that each image split is named 18_39.png, 19_39.png etc? In this example each grid is 128x128px.

import cv2
img = cv2.imread('sunset.png')

for r in range(0,img.shape[0],128):
    for c in range(0,img.shape[1],128):
        cv2.imwrite(f"split/img{r-128}_{c-128}.png",img[r:r 128, c:c 128,:])

CodePudding user response:

You need to modify the for loop that iterates through Y- axis in reverse. enter image description here

  • Related