ruby-vips icon indicating copy to clipboard operation
ruby-vips copied to clipboard

Basic image trim with background

Open AlecRust opened this issue 3 years ago • 4 comments

I'm switching to VIPS from ImageMagick since Rails has made it the default in version 7, via image_processing gem.

I'm struggling with a basic "trim" to remove excess pixels (white in this case) around a product image:

image

As mentioned in this blog post with ImageMagick these are the options to trim:

{
  fuzz: '1%',
  trim: true
}

I'm not sure what the equivalent is with VIPS. From my reading I expected find_trim to work i.e.

{
  find_trim: true
}

# OR

{
  find_trim: {
    threshold: 10
  }
}

But this doesn't work. Any ideas what I'm doing wrong?

I'd also like to remove the white background entirely in the case of logos i.e. replace white with transparent. With ImageMagick it's:

{
  transparent: 'white'
}

But again I can find no VIPS equivalent for this. These seem like quite common transforms that should work with similar options?

AlecRust avatar Jan 14 '22 14:01 AlecRust

Hi Alec, you'd need to ask image_processing (it's not my project), but at the CLI it'd be:

$ vips find_trim bottle.png 
95
20
61
233

Or in Ruby:

$ irb
irb(main):001:0> require "vips"
=> true
irb(main):002:0> x = Vips::Image.new_from_file "bottle.png"
=> #<Image 221x291 uchar, 4 bands, srgb>
irb(main):003:0> x.find_trim
=> [95, 20, 61, 233]

You can draw a box to visualize the rect with:

irb(main):004:0> x = x.draw_rect 0, *x.find_trim
=> #<Image 221x291 uchar, 4 bands, srgb>
irb(main):005:0> x.write_to_file "x.png"
=> nil

Making:

x

jcupitt avatar Jan 14 '22 15:01 jcupitt

Oh heh the github downsizer as made the 1px box invisible. Click on the image to see the rect.

jcupitt avatar Jan 14 '22 15:01 jcupitt

.... sorry, last post, as I recall image_processing lets you drop down to ruby-vips as part of the chain of operations, so you'd need to add a line like:

x = x.crop *x.find_trim

somewhere. Have a look at the image_processing docs.

jcupitt avatar Jan 14 '22 15:01 jcupitt

Hi Alec, you'd need to ask image_processing

Yeah, I wondered if that was the right place but figured all that gem does is pass options through to VIPS.

Sounds like perhaps image_processing would need to add find_trim method to make it as easy as { find_trim: true }, as it's not mentioned in the docs.

Will open an issue there about this. Thanks for your useful reply anyway!

AlecRust avatar Jan 14 '22 15:01 AlecRust