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
添加回答
舉報(bào)