torch / image

An Image toolbox for Torch.
Other
208 stars 141 forks source link

Unusual behavior of image saving and loading #159

Closed shubhashis-k closed 8 years ago

shubhashis-k commented 8 years ago

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.

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? 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)
deltheil commented 8 years ago

First, as pointed out by @andreaskoepf on gitter, you must use torch.eq for an element-wise comparison (or equal if you use a version >= torch/torch7@ad65230).

That said i1 is a double tensor with range on [0, 255]:

> i1:type()
torch.DoubleTensor  
> i1:min()
0   
> i1:max()
247  

With such a range you must convert it back to a byte tensor before saving, otherwise it will be saturated which is not what you want. In other words do:

i1 = testData.data[2]:byte()
image.save("1.png", i1)

Then:

i2 = image.load("1.png", 3, "byte")
if i1:eq(i2):all() then print("same") end
soumith commented 8 years ago

can you not post the same question at three different places (gitter, github issues and stackoverflow), as is we spend a lot of time helping out people, we cant spend 3x the time because you were creative.