2016-01-21 97 views

回答

0

我結束了使用scikit-解決我的問題圖像和numpy python模塊。示例代碼如下:

from skimage import io, draw 
import numpy 

# read in the image as a numpy array 
image = io.imread("image.png") 
# setup a list of coords in the polygon 
polygon = numpy.array([[100, 100], [200, 100], [200, 200], [100, 200]]) 
# Get a 2D list of pixels in the polygon 
pixels = image[draw.polygon(polygon[:, 1], polygon[:, 0])] 
# Use the channels of each pixel to get averages and convert them to ints 
channels = numpy.average(pixels, 0).astype(int) 
# Print! 
print(channels) 
1

我會使用你的座標來使用-draw創建感興趣區域的蒙版。然後這可以用於將形狀外部的區域轉換爲透明區域。然後像以前一樣將圖像縮小到1x1像素。

+0

我有一段時間,感覺像實現您的答案 - 希望沒關係。 –

+0

是的,沒關係 – Bonzo

0

@ Bonzo的答案的骨頭上放一些肉的種類,這裏有一種方法可以做到這一點。

convert image.jpg        \ 
    \(+clone -evaluate set 0 -fill white  \ 
     -draw "polygon 400,50 450,150 200,220" \ 
     -write mask.png -transparent black  \ 
    \) -compose copyopacity -composite   \ 
    -write masked.png -resize 1x1!    \ 
    -alpha off -depth 8 -format "%[pixel:p{0,0}]\n" info: 

srgb(145,114,94) 

所以,說... 「加載您的原始圖像,並從主圖像做括號下面的東西就在身邊,流連忘返。複製圖像(-clone)並使其全黑(-evaluate set 0),併爲我們即將繪製的多邊形填充顏色爲白色(-fill white),繪製多邊形(-draw "polygon ...")並將其保存在名爲mask.png的文件中,現在讓圖像的所有黑色區域都透明。有一個蒙版,現在通過關閉圓括號回到原始圖像,從蒙版圖像中複製透明圖像並將其應用於原始圖像(-compose copyopacity -composite),將蒙版圖像寫爲masked.png。Res將其平均爲1x1像素。現在輪到透明度關閉,使該單個像素固體和終端它是人類可讀的條款上寫「

你可以看到中間的圖像 - 這裏是mask.png

enter image description here

這裏是masked.png

enter image description here

是的,我知道這並不完全匹配,但這只是因爲...如果你沒有提供座標,我不得不猜測它們!把你自己的號碼放入-draw polygon部分,它會正常工作。

您實際上不需要任何一箇中間圖像,我只保存它們用於調試和演示目的,因此您可以從上面的命令中刪除-write mask.png-write masked.png

驗證

只是爲了檢查舍入和平均的準確性,您可以用數學計算的平均顏色。您使用與上述相同的基本技術,但通過計算遮罩中白色像素的比例來計算平均值的比例因子,然後遮罩圖像並查看遮罩中R,G和B的平均值圖像和縮放它們按比例...

convert -respect-parentheses image.jpg   \ 
    \(+clone -evaluate set 0 -fill white   \ 
    -draw "polygon 400,50 450,150 200,220"  \ 
    -format "Factor:%[fx:1/mean]\n" -write info: \ 
    \) -compose multiply -composite -verbose info: \ 
    | grep -E "Factor:|Red:|Green:|Blue:|mean:" 

Factor:21.4019 
Red: 
    mean: 6.70078 (0.0262776) 
Green: 
    mean: 5.31762 (0.0208534) 
Blue: 
    mean: 4.40595 (0.0172782) 

# Check the Red value - original method gave srgb(145,114,94) 
echo "6.70078*21.4019"|bc 
143.40942 

# Check the Green value 
echo "5.317*21.4019"|bc 
113.7939 

# Check the Blue value 
echo "4.40595*21.4019"|bc 
94.29570 

順便說一句,這個平均作品已在此:

convert -size 100x100 xc:"srgb(145,114,94)" average.png 

enter image description here