Issue
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:
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,:])
Solution
You need to modify the for
loop that iterates through Y- axis in reverse. See how to loop backwards using for
loop
for r in range(img.shape[0], 0, -128):
for c in range(0, im.shape[1], 128):
#cv2.imshow('im',img[r-128:r, c:c+128,:])
cv2.imwrite(f"split/img{r}_{c+128}.png", img[r-128:r, c:c+128,:])
#cv2.waitKey()
Uncomment the lines to display the cropped images
Update:
a = 18
b = 39
for i, r in enumerate(range(img.shape[0], 0, -128)):
for j, c in enumerate(range(0, im.shape[1], 128)):
print(a+j, "_", b+i)
filename = str(a+j) + "_" + str(b+i)
cv2.imwrite(f"split/img{filename}.png", img[r-128:r, c:c+128,:])
Images stored in the folder:
Answered By - Jeru Luke
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.