[英]Minimize image area while preserving a certain metric
I have a picture and I want to find the crop with the minimal area that at the same time retains a certain percentage of the edge energy. 我有一张照片,我想找到面积最小的作物,同时保留一定比例的边缘能量。
My take on this was to formulate this as a optimization problem and let scipy's constrained optimizers solve it [code see below]. 我对此的看法是将其表述为优化问题,然后让scipy的约束优化器解决此问题[代码见下文]。 This apparently is problematic since it is an integer problem (croping takes the integer coordinates of the top-left and down-right corners as parameters).
这显然是有问题的,因为这是一个整数问题 (裁剪将左上角和右下角的整数坐标作为参数)。 And indeed
fmin_cobyla
fails to find a solution after some 20s runtime, while fmin_slsqp
fails after one iteration with " Singular matrix C in LSQ subproblem (Exit mode 6) ". 确实,
fmin_cobyla
在大约20 fmin_slsqp
运行时间后未能找到解决方案,而fmin_slsqp
在“ LSQ子问题中的奇异矩阵C(退出模式6) ”的一次迭代后失败。
Any ideas on how I might tackle this problem otherwise? 关于如何解决这个问题的任何想法吗? Is there by chance a library that handles optimization problems on images?
是否有一个图书馆可以处理图像的优化问题?
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
I would probably ignore the integer requirement for the corners of the cropped area and solve the relaxed problem. 我可能会忽略对裁切区域拐角的整数要求,然后解决松弛问题。 Then consider moving the cropped edges in or out to the nearest whole pixel.
然后考虑将裁切后的边缘移入或移出到最近的整个像素。 If it is for aesthetic purposes, the +/- part pixel probably doesn't matter.
如果是出于美学目的,则+/-部分像素可能无关紧要。 If it has to be correct, there are only four edges to consider in two places each so should not be a big deal to find the one out of 16 choices which is best.
如果必须正确,则每个地方只有四个要考虑的方面,因此从16个选择中最好的一个中寻找一个应该不是什么大问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.