2011-09-28 119 views
0

讓我們假設圖像存儲爲一個PNG文件,我需要放下每一個奇數行,並將結果水平調整爲50%,以保持縱橫比。如何在Python中對圖像進行隔行掃描?

結果必須有原始圖像分辨率的50%。

它不足以推薦像PIL這樣的現有圖像庫,我希望看到一些工作代碼。

UPDATE - 即使這個問題收到了正確的答案,我想提醒其他人PIL是不是一個偉大的形狀,在項目網站沒有更新的幾​​個月,有一個bug traker和無鏈接列表活動相當低。我驚訝地發現用PIL保存的一個簡單的BMP文件沒有被PIL加載。

+0

讓我明確 - 你在問如何使用PIL來做到這一點?或者你問如何在沒有PIL的情況下做到這一點? –

+1

看起來像PIL的「im.transform」可能會有用。如果沒有,就有'im.resize',你可以對其餘的像素級操作。你有5100代表和金徽章,所以我認爲你可以從那裏拿走。 –

+0

PIL沒問題,我更新了問題。我正在尋找一些工作代碼,爲其他人記錄程序。我確信我自己可以編寫代碼,但我無聊回答自己的問題。 – sorin

回答

1

是它必須保持每一個偶數行(其實,定義「偶」 - 你從10計數爲圖像的第一行)

如果你不介意這行是下降,使用PIL:

from PIL import Image 
img=Image.open("file.png") 
size=list(img.size) 
size[0] /= 2 
size[1] /= 2 
downsized=img.resize(size, Image.NEAREST) # NEAREST drops the lines 
downsized.save("file_small.png") 
+0

This因爲'resize'的默認過濾器是'NEAREST',它會拋棄所有其他像素。 +1爲一個非常簡單的解決方案。 –

+0

感謝馬克 - 我應該提到我使用'NEAREST'默認。 –

0

我最近想對一些立體圖像進行去隔行處理,提取左眼和右眼的圖像。對於我這樣寫道:

from PIL import Image 

def deinterlace_file(input_file, output_format_str, row_names=('Left', 'Right')): 
    print("Deinterlacing {}".format(input_file)) 
    source = Image.open(input_file) 
    source.load() 
    dim = source.size 

    scaled_size1 = (math.floor(dim[0]), math.floor(dim[1]/2) + 1) 
    scaled_size2 = (math.floor(dim[0]/2), math.floor(dim[1]/2) + 1) 

    top = Image.new(source.mode, scaled_size1) 
    top_pixels = top.load() 
    other = Image.new(source.mode, scaled_size1) 
    other_pixels = other.load() 
    for row in range(dim[1]): 
     for col in range(dim[0]): 
      pixel = source.getpixel((col, row)) 
      row_int = math.floor(row/2) 
      if row % 2: 
       top_pixels[col, row_int] = pixel 
      else: 
       other_pixels[col, row_int] = pixel 


    top_final = top.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio 
    other_final = other.resize(scaled_size2, Image.NEAREST) # Downsize to maintain aspect ratio 
    top_final.save(output_format_str.format(row_names[0])) 
    other_final.save(output_format_str.format(row_names[1])) 

output_format_str應該是這樣的:"filename-{}.png"其中{}將與該行的名稱來代替。

請注意,它最終的圖像是原始大小的一半。如果你不想要這個,你可以旋轉最後的縮放步驟

它不是最快的操作,因爲它逐個像素地穿過,但我看不到從圖像中提取行的簡單方法。

相關問題