问题描述:

Its not about cropping an image in OpenCV. I know how to do it, for example: Image[200:400, 100:300] # Crop from x, y, w, h -> 100, 200, 300, 400. What I am trying to do is create multiple segments of the Image, which do not exceed Image's Width/Height obviously.

So precisely, if an Image is 720x640 resolution,and I need to split this image in multiple blocks, say it 100x100 Fixed blocks, so how to achieve this exactly in OpenCV using Python?

网友答案:
import cv2

def segmentize (image_path, segment_width=200, segment_height=50):
    # Croping Formula ==> y:h, x:w
    idx, x_axis, x_width,  = 1, 0, segment_width
    y_axis, y_height = 0, segment_height
    img = cv2.imread(image_path)
    height, width, dept = img.shape
    while y_axis <= height:
        while x_axis <= width:
            crop = img[y_axis:y_height, x_axis:x_width]
            x_axis=x_width
            x_width+=segment_width
            cropped_image_path = "crop/crop%d.png" % idx
            cv2.imwrite(cropped_image_path, crop)
            idx+=1
        y_axis += segment_height
        y_height += segment_height
        x_axis, x_width = 0, segment_width
相关阅读:
Top