Crop an image to smaller size from left to right and top to bottom using OpenCV

Issue

I have an image 315×581. I want to crop it in 28×28 from top left to bottom right, then I need to save each 28×28 image in folder.
I could crop just one image from y1=0 to y2=28 and x1=0 to x2=28.

First problem is: I used cv2.imwrite(“cropped.jpg”, cropped) to save this small image, but It doesn’t save it, provided that it works some line above.

Second problem is: How can I write a code which it keeps on cropping the image in 28×28 from left to right and top to bottom and save each subimage.
I used for loop, but I don’t know how to complete it.
Thank you so much for any help.

Here this is my code,

``````import cv2
import numpy as np
from PIL import Image
import PIL.Image
import os
import gzip
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
#%%

# combine foreground+background

cv2.imshow('final1LL',final1LL)
cv2.waitKey(100)
final1LL.size
final1LL.shape

# Save the image
cv2.imwrite('final1LL.jpg',final1LL)

# crop the image using array slices -- it's a NumPy array
# after all!

y1=0
x1=0
for y2 in range(0,580,28):
for x2 in range(0,314,28):
cropped = final1LL[0:28, 0:28]
cv2.imshow('cropped', cropped)
cv2.waitKey(100)
cv2.imwrite("cropped.jpg", cropped)``````

Solution

Your approach is good, but there is some fine tuning required. The following code will help you:

``````import cv2

filename = 'p1.jpg'

interval = 100
stride = 100
count = 0
print img.shape

for i in range(0, img.shape[0], interval):
for j in range(0, img.shape[1], interval):
print j
cropped_img = img[j:j + stride, i:i + stride]  #--- Notice this part where you have to add the stride as well ---
count += 1
cv2.imwrite('cropped_image_' + str(count) + '_.jpg', cropped_img)   #--- Also take note of how you would save all the cropped images by incrementing the count variable ---

cv2.waitKey()
``````

Original image:

Cropped image 1

Cropped image 2

Cropped image 3