Search code examples
machine-learningtorch

Unusual behavior of image saving and loading in torch7


I noticed an unusual behavior with torch7. I know a little about torch7. So I don't know how this behavior can be explained or corrected.

So, I am using CIFAR-10 dataset. Simply I fetched data for an image from CIFAR-10 and then saved it in my directory. When I loaded that saved image, it was different.

Here is my code -

require 'image'

i1 = testData.data[2] --fetching data from CIFAR-10
image.save("1.png", i) --saving the data as image

i2 = image.load("1.png") --loading the saved image

if(i1 == i2) then --checking if image1(i1) and image2(i2) are different
print("same") 
end

Is this behavior expected? I thought png was supposed to be lossless.

If so how this can be corrected?

Code for loading CIFAR-10 dataset-

-- load dataset
  trainData = {
     data = torch.Tensor(50000, 3072),
     labels = torch.Tensor(50000),
     size = function() return trsize end
  }
  for i = 0,4 do
     local subset = torch.load('cifar-10-batches-t7/data_batch_' .. (i+1) .. '.t7', 'ascii')
     trainData.data[{ {i*10000+1, (i+1)*10000} }] = subset.data:t()
     trainData.labels[{ {i*10000+1, (i+1)*10000} }] = subset.labels
  end
  trainData.labels = trainData.labels + 1

  local subset = torch.load('cifar-10-batches-t7/test_batch.t7', 'ascii')
  testData = {
     data = subset.data:t():double(),
     labels = subset.labels[1]:double(),
     size = function() return tesize end
  }
  testData.labels = testData.labels + 1
  testData.data = testData.data:reshape(10000,3,32,32)

Solution

  • == operator compares pointers to two tensors, not contents:

    a = torch.Tensor(3, 5):fill(1)
    b = torch.Tensor(3, 5):fill(1)
    print(a == b)
    > false
    print(a:eq(b):all())
    > true