1
$\begingroup$

I would like to rotate an image if and only if, the aspect ratio of the image is > 1, else just print the original picture and afterwards use the data.

My problem is that Mathematica writes "expecting an image instead of null", because of the If statement.

$\endgroup$
  • 2
    $\begingroup$ I don't see any code you've written. In any event, what you can do is have the second argument of ImageRotate[] be a conditional. $\endgroup$ – J. M. will be back soon Oct 13 '15 at 9:19
3
$\begingroup$

Here's one method you can try, although you don't specify exactly how you would like the image to be rotated - you can edit the 90 Degree angle to your own requirements.

test = ImageResize[ExampleData[{"TestImage", "Mandrill"}], {256, 256}];
crop = ImageCrop[test, {128, 256}]

enter image description here

rotateImage = ImageRotate[#, If[ImageAspectRatio[#] > 1, 90 Degree, 0]] &;    
rotateImage[crop]

enter image description here

Edit

A comment suggests a different order for the rotation function, which doesn't call ImageRotate[] unnecessarily, namely:

rotateImage2 = If[ImageAspectRatio@# > 1, ImageRotate[#, 90 Degree], #] &;

This avoids a performance overhead if no rotation is required, since image is faster than ImageRotate[image, 0 Degree].

$\endgroup$
  • $\begingroup$ Why not use ImageAspectRatio[]? $\endgroup$ – J. M. will be back soon Oct 13 '15 at 9:29
  • $\begingroup$ @J.M. because I forgot about that one? Now changed :-) $\endgroup$ – dr.blochwave Oct 13 '15 at 9:30
  • $\begingroup$ …upvoted now. :) $\endgroup$ – J. M. will be back soon Oct 13 '15 at 12:59
  • 2
    $\begingroup$ I would do it the other way round to prevent an unnecessary call to ImageRotate if no rotation is needed: rotateImage = If[ImageAspectRatio@#>1,ImageRotate[#,90 Degree],#]& as If has the HoldRest attribute. $\endgroup$ – LLlAMnYP Oct 13 '15 at 13:52
  • 1
    $\begingroup$ Can't test that, I'm afraid, our license server suddenly died :( I do recall, that image-manipulating functions tend to be slow. $\endgroup$ – LLlAMnYP Oct 13 '15 at 14:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.