Skip to content

Instantly share code, notes, and snippets.

@achalddave
Last active September 6, 2016 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save achalddave/d9e7a6416996c648c6e75355e3f87df1 to your computer and use it in GitHub Desktop.
Save achalddave/d9e7a6416996c648c6e75355e3f87df1 to your computer and use it in GitHub Desktop.
-- Exhibits differences between torch's image.scale and opencv's resize
-- function.
local cv = require 'cv' -- https://github.com/VisionLabs/torch-opencv
require 'cv.imgcodecs'
require 'cv.imgproc'
require 'image'
local path = './foobar.png'
-- RGB, shape channels * height * width
local torch_image = image.load(path, 3, 'byte')
-- BGR, shape height * width * channels
local opencv_image = cv.imread({path, cv.IMREAD_COLOR}):byte()
-- Ensure the two images are equal. This should, and does, pass.
assert(torch.all(torch.eq(opencv_image[{{}, {}, 1}], torch_image[3])) and
torch.all(torch.eq(opencv_image[{{}, {}, 2}], torch_image[2])) and
torch.all(torch.eq(opencv_image[{{}, {}, 3}], torch_image[1])))
torch_image = image.scale(torch_image, 256, 256)
opencv_image = cv.resize({opencv_image, {256, 256}})
if not (torch.all(torch.eq(opencv_image[{{}, {}, 1}], torch_image[3])) and
torch.all(torch.eq(opencv_image[{{}, {}, 2}], torch_image[2])) and
torch.alltorch.eq(opencv_image[{{}, {}, 3}], torch_image[1]))
then
-- This prints, although it shouldn't.
print('The two images are not equal!')
end
-- Save torch and opencv images.
image.save('torch-resized.png', torch_image)
-- Convert opencv to be RGB, channels*width*height shape, and save it.
local opencv_clone = opencv_image:clone():permute(3, 1, 2) -- h*w*c -> c*h*w
opencv_clone[1] = opencv_image[{{}, {}, 3}]
opencv_clone[3] = opencv_image[{{}, {}, 1}]
image.save('opencv-resized.png', opencv_clone)
print('See images at torch-resized.png and opencv-resized.png')
@achalddave
Copy link
Author

achalddave commented Sep 6, 2016

The differences are easy to spot if you open the two images in two tabs and flip between them.

Original image (rgb16-2x1.png):
foobar

Torch resized (torch-resized.png):
torch-resized

OpenCV resized (opencv-resized.png):
opencv-resized

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment