圖像預處理-大圖切割-python實現


簡介

深度學習中,數據集的預處理往往是很基礎的一步,很多場景都需要將一張大圖進行切割。本篇提供一種重疊矩形框的生成方法,數據集中的圖像尺寸可以不同,根據生成的重疊矩形框可以crop出相應的圖像區域。主要難點在於函數不假設圖像的尺寸大小。

實現

以下是重疊矩形框的生成函數,是根據右下角的坐標來確定左上角的坐標,如果右下角的點超過了圖像邊緣,則讓矩形的右下角等於邊緣值。循環會讓右下角的坐標往右和往下多走一個stride,這樣可以將邊緣部分的圖像也包含進來。

#encoding=utf-8

def get_fixed_windows(image_size, wind_size, overlap_size):
    '''
    This function can generate overlapped windows given various image size
    params:
        image_size (w, h): the image width and height
        wind_size (w, h): the window width and height
        overlap (overlap_w, overlap_h): the overlap size contains x-axis and y-axis

    return:
        rects [(xmin, ymin, xmax, ymax)]: the windows in a list of rectangles
    '''
    rects = set()

    assert overlap_size[0] < wind_size[0]
    assert overlap_size[1] < wind_size[1]

    im_w = wind_size[0] if image_size[0] < wind_size[0] else image_size[0]
    im_h = wind_size[1] if image_size[1] < wind_size[1] else image_size[1]

    stride_w = wind_size[0] - overlap_size[0]
    stride_h = wind_size[1] - overlap_size[1]

    for j in range(wind_size[1]-1, im_h + stride_h, stride_h):
        for i in range(wind_size[0]-1, im_w + stride_w, stride_w):
            right, down = i+1, j+1
            right = right if right < im_w else im_w
            down  =  down if down < im_h  else im_h

            left = right - wind_size[0]
            up   = down  - wind_size[1]

            rects.add((left, up, right, down))      

    return list(rects)


if __name__ == "__main__":
    image_size = (1780, 532)
    wind_size = (800, 600)
    overlap_size = (300, 200)

    rets = get_fixed_windows(image_size, wind_size, overlap_size)

    for rect in rets:
        print(rect)
'''
# output
(0, 0, 800, 600)
(500, 0, 1300, 600)
(980, 0, 1780, 600)
'''

效果

總結

實在不知道寫什么了,把之前項目里的一個圖像預處理代碼po出來。嗯🤔,還是要堅持定時寫點東西。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM