0

I'm trying to crop an image using numpy. I'd like to divide one picture into nine and save it.

Write the function and enter the desired area and length to get the desired picture. However, I have to enter 9 times to get 9 photos. So I'd like to use repetition to get nine pictures if I enter it once. I tried to write using the for loop in the def, but it didn't work out, so I'm asking you this question. Thank you!

def crop(img, start_pos, length, width):
    img_shape = img.shape
    row = int(img.shape[0])
    column = int(img.shape[1])
    length = abs(length)
    width = abs(width)
    row = abs(row)
    column = abs(column)
    
    #for i in row()
    
    #start_row = start_pos if start_pos >= 0 else 0
    
    if start_pos >= 0:
        start_row = start_pos
    else:
        start_row = 0
    
    start_column = start_row
    
    end_row = length + start_row
    
    if end_row <= img_shape[0]:
        end_row = end_row
    else:
        end_row = img_shape[0]
        
        
    end_column = width + start_column
    
    if end_column <= img_shape[1]:
        end_column = end_column
    else:
        end_column = img_shape[1]
         
    
    print("start row:" , start_row)
    print("end row:" , end_row)
    print("start column:" , start_column)
    print("end column:" , end_column)
    #print("divide:", divide)
    
    #for i in row():
        #row = row + 100
        #if row <= img_shape[0]:
        #print(row)
            
            
        
    img_crop = img[start_row:end_row, start_column:end_column]
    
    save = cv2.imwrite('C:/Users/USER/jupyter/crop_image/chicken_001_crop.jpg', img_crop)
    
    return save
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • What are the `9 times` you mention? Do you mean that you have to call `crop()` nine times? If so, please show that code instead. – quamrana Feb 05 '22 at 17:06
  • Does this answer your question? [Slice 2d array into smaller 2d arrays](https://stackoverflow.com/questions/16856788/slice-2d-array-into-smaller-2d-arrays) – Paul Feb 05 '22 at 17:16

0 Answers0