智能裁剪图像

Smart cropping image

我正在寻找一种可用于自动裁剪多个图的方法.. 无需手动设置裁剪框大小。

我需要像这样裁剪频谱图列表,

其中我只需要实际的情节,除此之外别无其他。只是情节。

目前我是这样裁剪的。

print "Hstacked Image"
images1 = Image.open(spectogram_path_train+"/"+name+"_plot_static_conv.png")
images2 = Image.open(spectogram_path_train+"/"+name+"_plot_delta_conv.png")
images3 =      Image.open(spectogram_path_train+"/"+name+"_plot_delta_delta_conv.png")

box = (100,55,592,496)
cropped1  = images1.crop(box)
cropped2  = images2.crop(box)
cropped3  = images3.crop(box)

width1, height1 = cropped1.size
width2, height2 = cropped2.size
width3, height3 = cropped3.size

sum_width  = width1 + width2 + width3
max_height = max(height1,height2,height3)

new_im = Image.new('RGB',(sum_width,max_height))
x_offset = 0

for im in [cropped1,cropped2,cropped3]:
    new_im.paste(im,(x_offset,0))
    x_offset+=im.size[0]

new_im.save(spectogram_path_train+"/"+name+"_plot_hstacked.png")

这些框值设置为裁剪此图像。框的左侧和下方参数对于每个绘图始终相同,但右侧可能不同,必须为每个绘图自动确定。

我正在寻找一种智能作物,它能够去除彩色图以外的所有内容。

我不知道 Python,但你可以在没有任何 high-level 语言的终端上使用 ImageMagick 来做到这一点,大多数 Linux 发行版,适用于 macOS 和 Windows。

首先,请注意您的图像出于某种原因有一个多余的 alpha 通道,所以我将其关闭。

然后,我注意到您感兴趣的所有内容都是饱和颜色,所有无关文本都是 black/grey 且不饱和,因此我会转向饱和度作为判别式。这个命令,输入到终端,加载你的图像并将所有像素设置为黑色,即零,它们是不饱和的,并在其他地方保留它们的当前值。然后修剪边框并保存结果。

convert spectrum.png -alpha off -fx "saturation<0.2?0:u" -trim z.png

如果我现在再次 运行 该命令,但只提取顶部单行像素,并寻找第一个黑色像素,我就会知道在哪里裁剪:

convert spectrum.png -alpha off -fx "saturation<0.2?0:u" -trim +repage -crop x1! txt: | awk -F, '/black/{print ;exit}'

496

因此,我需要在第 496 列进行裁剪,我使用的是:

convert spectrum.png -alpha off -fx "saturation<0.2?0:u" -trim +repage -crop 496x+0+0 z.png

如果我想自动化整个过程,我可以这样做:

x=$(convert spectrum.png -alpha off -fx "saturation<0.2?0:u" -trim +repage -crop x1! txt: | awk -F, '/black/{print ;exit}')
convert spectrum.png -alpha off -fx "saturation<0.2?0:u" -trim +repage -crop ${x}x+0+0 y.png

所以..我决定听从@martineau 的建议并制定了一个利用它的解决方案。

images1 = Image.open(static)
images2 = Image.open(delta)
images3 = Image.open(delta_delta)

data_numpy = np.array(images1)
number = 0
right = 0

for i in data_numpy[55,:]:
#    print i
    number+=1
    if i[0] == 234 and i[1] == 234 and i[2] == 242 and i[3] == 255 and number > 100:
#        print "Found it!"
        right = number
        break
    if i[0] == 255 and i[1] == 255 and i[2] == 255 and i[3] == 255 and number > 100:
        right = number
        break
#print right

box = (100,55,right,496)

cropped1  = images1.crop(box)
cropped2  = images2.crop(box)
cropped3  = images3.crop(box)

我希望代码不言自明,如果不是..

for循环遍历图像(由于图的大小,只需要检查一行),并找到与灰色相同的像素位置。当找到时,for 循环会中断,并且会创建一个适合所需大小的框。