第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

如何用python將圖片劃分為等間距的正方形?

如何用python將圖片劃分為等間距的正方形?

MMTTMM 2022-06-28 10:02:55
我正在嘗試使用 PIL 并定義我自己的函數(shù),該函數(shù)將圖像和 square_size(寬度或高度)作為參數(shù),然后將圖像分成一系列所述大小的較小正方形。我不明白 PIL 的裁剪方法。它接受一個(gè)(上、左、右、下)。左上、右上等系統(tǒng)似乎更有用。我在哪里,卡住的是編寫代碼,可以找到這些坐標(biāo)應(yīng)該是什么,從原點(diǎn)開始,給定一個(gè)正方形大小。有任何想法嗎?這是行不通的。def parse_image(source, square_size):    src = Image.open(source)    dimensions = src.size    max_up = int(src.height/square_size)    max_right = int(src.width/square_size)    tl = 0    tr = square_size    bl = square_size * src.width + 1     br = bl + square_size    test = src.crop((tl,tr,bl,br))    test.save('test.jpg')    test.show()
查看完整描述

1 回答

?
冉冉說

TA貢獻(xiàn)1877條經(jīng)驗(yàn) 獲得超1個(gè)贊

假設(shè)square_size是一個(gè)定義每邊長度的 int 并且我們想要多個(gè)圖像作為結(jié)果。下面的代碼未經(jīng)測試,但應(yīng)該可以解決您的問題


def parse_image(source, square_size): 

    src = Image.open(source)

    width, height = src.size

    image_results = []

    for x in range(0, width, square_size): #

        for y in range(0, height, square_size):

            top_left = (x, y) #left top of the rect

            bottom_right = (x+square_size, y+square_size) #right bottom of the rect

            #the current format is used, because it's the cheapest

            #way to explain a rectange, lookup Rects

            test = src.crop((top_left[1], top_left[0], bottom_right[0], bottom_right[1]))

            image_results.append(test)


    return image_results

讓我知道是否有任何問題!


編輯,我受到一個(gè)候選答案的啟發(fā),這個(gè)解決方案奏效了。


def parse_image(source, square_size, print_coords=False):

    src = Image.open(source)

    dimensions = src.size

    print(f"image dimensions: {src.size}")

    max_down = int(src.height/square_size) * square_size + square_size

    max_right = int(src.width/square_size) * square_size + square_size


    tl_x = 0

    tl_y = 0

    br_x = square_size 

    br_y = square_size


    count=0

    for y in range(square_size,max_down,square_size):

        for x in range(square_size,max_right,square_size):

            count +=1

            sample = src.crop((tl_x,tl_y,br_x,br_y))

            sample.save(f"{source[:-4]}_sample_{count}_x{tl_x}_y{tl_y}.jpg")

            if print_coords == True: 

                print(f"image {count}: top-left (x,y): {(tl_x,tl_y)}, bottom-right (x,y): {(br_x,br_y)}")

            tl_x = x

            br_x = x + square_size

        tl_x =0

        br_x = square_size

        tl_y = y

        br_y = y + square_size


查看完整回答
反對(duì) 回復(fù) 2022-06-28
  • 1 回答
  • 0 關(guān)注
  • 137 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)