RMagick convert problem - rmagick

In linux i'm doing the below to convert a multipage PDF into images resized and with a high resolution:
convert -verbose -colorspace RGB -resize 800 -interlace none -density 300 -quality 80 test.pdf test.jpg
For the life of me, i can't seem to reproduce this EXACT command using RMagick. I tried something like this below but the image doesn't have the size/resolution i want. Any ideas?
Magick::ImageList.new('test.pdf').each_with_index { |img, i|
img.resize_to_fit!(800, 800)
img.write("test-#{i}.jpg") {
self.quality = 80
self.density = '300'
self.colorspace = Magick::RGBColorspace
self.interlace = Magick::NoInterlace
}
}
Cheers,
G.

Use block with quality options for method new instead of method write:
Magick::ImageList.new('test.pdf') do
self.quality = 80
self.density = '300'
self.colorspace = Magick::RGBColorspace
self.interlace = Magick::NoInterlace
end.each_with_index do |img, i|
img.resize_to_fit!(800, 800)
img.write("test-#{i}.jpg")
end
Not sure actually about colorspace and interlace options,
but it definitely works for quality and density.

Related

How to use readClipboard to read a bitmap when using R?

I don't managed to read a bitmap which is in the Windows clipbard.
I first check the cliboard :
getClipboardFormats()
which give
[1] "bitmap" "DIB" "shell"
Then I tried :
image = readClipboard(format=2, raw=FALSE)`
and
image = readClipboard(format=2, raw=TRUE)
but I always obtain a NULL value for image !
Can someone explain to me how to do it?

CoreML Catalyst MPSNNReduceFeatureChannelsArgumentMax returns all zeros

I'm using CoreML for image segmentation. I have a VNCoreMLRequest to run a model that returns a MLMultiArray. To accelerate processing the model output, I use MPSNNReduceFeatureChannelsArgumentMax to reduce the multiarray output to a 2D array which I then convert to a grayscale image.
This works great on iOS, but when running on Mac as a catalyst build, the output 2D array is all zeros.
I'm running Version 12.2 beta 2 (12B5025f) on an iMac Pro. I'm not seeing any runtime errors. MPSNNReduceFeatureChannelsArgumentMax appears to not work on Mac Catalyst.
I'm able to reduce the channels directly on the cpu by looping through all the array dimensions but it's very slow. This proves the model output works, just the metal reduce features fails.
Anyone else using CoreML and Catalyst?
Here's the bit of code that doesn't work:
let buffer = self.queue.makeCommandBuffer()
let filter = MPSNNReduceFeatureChannelsArgumentMax(device: self.device)
filter.encode(commandBuffer: buffer!, sourceImage: probs, destinationImage: classes)
// add a callback to handle the buffer's completion and commit the buffer
buffer?.addCompletedHandler({ (_buffer) in
let argmax = try! MLMultiArray(shape: [1, softmax.shape[1], softmax.shape[2]], dataType: .float32)
classes.readBytes(argmax.dataPointer,
dataLayout: .featureChannelsxHeightxWidth,
imageIndex: 0)
// unmap the discrete segmentation to RGB pixels
guard var mask = codesToMask(argmax) else {
return
}
// display image in view
DispatchQueue.main.async {
self.imageView.image = mask
}
})

How to write lossless WebP files with PerlMagick

I'm trying to convert PNG files to lossless WebP in Perl with Graphics::Magick. Command line for that is:
$ gm convert in.png -define webp:lossless=true out.webp
My Perl code looks something like that:
use Graphics::Magick;
my $image = Graphics::Magick->new();
$image->Read("in.png");
my $image_data = $image->ImageToBlock(magick => "webp");
print $out_fh $image_data;
This code writes lossy WebP files perfectly, but how can I express the "-define" thing in terms of Perl API?
Thanks,
Update: looks like I need to call AddDefiniton API function (http://www.graphicsmagick.org/api/image.html#adddefinition). Looks like it's not exported via Perl API as of now.
I know it is of no help to you, but for those interested in how to do it in PHP, here is how:
$im = new \Gmagick($src);
$im->setimageformat('WEBP');
// Not completely sure if setimageoption() has always been there, so lets check first.
if (method_exists($im, 'setimageoption')) {
$im->setimageoption('webp', 'lossless', 'true');
}
$imageBlob = $im->getImageBlob();
$success = #file_put_contents($destination, $imageBlob);
For more webp options, check out this code

Saving a cropped image in R

I am using jpeg package to read an image into R. This creates an object of class nativeRaster. I take a portion of this image using [ operator. The resulting object is a matrix of integers. Attempting to save this object returns the error image must be a matrix or array of raw or real numbers. What should I do to be able to save this new image?
Below is a snippet to reproduce the error
imageFile = 'address of the jpg file'
outputFile = 'new file to write into'
image = jpeg::readJPEG(imageFile, native=TRUE)
output = image[1:10,1:10]
writeJPEG(image = output, target = outputFile)
I think the function writeJPEG takes image of type nativeRaster. I am not entirely sure about this but converting class of output to nativeRaster works for me.
class(output) <- "nativeRaster"
writeJPEG(image = output, target = outputFile)
Even though I was unable to find a solution, I am working around this by using solely imagemagick to crop the image.
system(paste('identify',
imageFile), intern = TRUE) %>%
regmatches(.,regexpr("(?<=[ ])[0-9]*?x[0-9]*?(?=[ ])",.,perl=T)) %>%
strsplit('x') %>% .[[1]] %>% as.double
will return the dimensions of the image and
system(paste0('convert "',imageFile,
'" -crop ',
sizeX,
'x',
sizeY,
'+',
beginningX,
'+',
beginningY,
' "',
outputFile,'"'))
will crop the image and save it to outputFile
Here sizeX and sizeY are desired dimensions of the cropped image and beginningX and beginningY designate the top left corner of the crop site on the image.

Most efficient way of displaying jpgs with bokeh? Image_rgba surprisingly slow

I've tried using the bokeh image_rgba method but found it to be very slow, I'm just displaying a 1000*500 px image and the html takes ~5 seconds to load (nothing is web based here, I have everything running/stored locally)
Again the code itself runs fast, itùs just displaying the image thqt is slow. I've been trying exqmples from the bokeh gallery and the speed is fine.
I'm thus wondering if there is anything I could do for the html to load faster? Is image_rgba the best way to go to display an image with bokeh?
This is the code I use:
pic = PIL.Image.open('/Users/blabla/eiffelTower.jpg')
self.imgArray = np.array(pic)
N1 = imgArray.shape[0]
N2 = imgArray.shape[1]
img = np.zeros((N1,prolongatedN2), dtype=np.uint32)
view = img.view(dtype=np.uint8).reshape((N1, N2, 4))
view[:N1,:N2,0] = self.imgArray[range(N1-1,-1,-1),:N2,0]
view[:N1,:N2,1] = self.imgArray[range(N1-1,-1,-1),:N2,1]
view[:N1,:N2,2] = self.imgArray[range(N1-1,-1,-1),:N2,2]
fig = bokeh.plotting.figure(plot_width = plot_width, plot_height=plot_height)
fig.image_rgba(image=[img], x=[0], y=[0],
dw=[plot_width], dh=[plot_height])
script, div = bokeh.embed.components(p.fig, INLINE)
output_file('testBokeh.html')
show(fig)
Again I'm quite surprised that displaying a locally stored 1000*500 pixels would be so slow.
FWIW, I do this, and it's very fast.
from __future__ import division
import numpy as np
from PIL import Image
from bokeh.plotting import figure, show, output_file
# Open image, and make sure it's RGB*A*
lena_img = Image.open('Lenna_rect.png').convert('RGBA')
xdim, ydim = lena_img.size
print("Dimensions: ({xdim}, {ydim})".format(**locals()))
# Create an array representation for the image `img`, and an 8-bit "4
# layer/RGBA" version of it `view`.
img = np.empty((ydim, xdim), dtype=np.uint32)
view = img.view(dtype=np.uint8).reshape((ydim, xdim, 4))
# Copy the RGBA image into view, flipping it so it comes right-side up
# with a lower-left origin
view[:,:,:] = np.flipud(np.asarray(lena_img))
# Display the 32-bit RGBA image
dim = max(xdim, ydim)
fig = figure(title="Lena",
x_range=(0,dim), y_range=(0,dim),
# Specifying xdim/ydim isn't quire right :-(
# width=xdim, height=ydim,
)
fig.image_rgba(image=[img], x=0, y=0, dw=xdim, dh=ydim)
output_file("lena.html", title="image example")
show(fig) # open a browser

Resources