簡體   English   中英

在保留特定指標的同時最小化圖像區域

[英]Minimize image area while preserving a certain metric

我有一張照片,我想找到面積最小的作物,同時保留一定比例的邊緣能量。

我對此的看法是將其表述為優化問題,然后讓scipy的約束優化器解決此問題[代碼見下文]。 這顯然是有問題的,因為這是一個整數問題 (裁剪將左上角和右下角的整數坐標作為參數)。 確實, fmin_cobyla在大約20 fmin_slsqp運行時間后未能找到解決方案,而fmin_slsqp在“ LSQ子問題中的奇異矩陣C(退出模式6) ”的一次迭代后失敗。

關於如何解決這個問題的任何想法嗎? 是否有一個圖書館可以處理圖像的優化問題?


from skimage.filters import sobel
from PIL import Image
from scipy.optimize import fmin_slsqp

def objective(x):
    # minimize the area
    return abs((x[2] - x[0]) * (x[3] - x[1]))

def create_ratio_constr(img):
    def constr(x):
        # 81% of the image energy should be contained
        x = tuple(map(int, x))
        crop = img.crop((x[0], x[1], x[2], x[3]))
        area_ratio = round(sum(list(crop.getdata())) /
                           float(sum(list(img.getdata()))), 2)
        if area_ratio == 0.81:
            return 0.0
        return -1
    return constr

def borders_constr(x):
    x = tuple(map(int, x))
    # 1st point is up and left of 2nd point
    rectangle = x[0] < x[2] and x[1] < x[3]

    # only positive values valid
    positive = x[0] > 0 and x[1] > 0

    if rectangle and positive:
        return 0.0
    return -1

img = Image.open("/some/path.jpg")
# get the edges
edges = Image.fromarray(sobel(img.convert("L")))

ratio_constr = create_ratio_constr(edges)
x = fmin_slsqp(objective,
               (0, 0, edges.size[0]-1, edges.size[1]-1),
               [borders_constr, ratio_constr],
               disp=1)

print x

我可能會忽略對裁切區域拐角的整數要求,然后解決松弛問題。 然后考慮將裁切后的邊緣移入或移出到最近的整個像素。 如果是出於美學目的,則+/-部分像素可能無關緊要。 如果必須正確,則每個地方只有四個要考慮的方面,因此從16個選擇中最好的一個中尋找一個應該不是什么大問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM