Different mean subtraction between c++ and python

440 views
Skip to first unread message

Jing Ye

unread,
Feb 9, 2017, 9:25:25 AM2/9/17
to Caffe Users


What's the difference between the following c++ code and python code? Both of them will load a same test.jpg(32x32) and subtract a mean matrix (255, 0, 0).


But the output images are apparently different. it's very strange.


Can any one help me?



test.jpg is




#include <caffe/caffe.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <algorithm>
#include <iosfwd>
#include <memory>
#include <string>
#include <utility>
#include <vector>

using namespace caffe;
using std::string;


int main(int argc, char** argv) {
    cv::Mat img = cv::imread("test.jpg", CV_LOAD_IMAGE_COLOR);
    cv::Mat mean = cv::Mat(32, 32, CV_32FC3, cv::Scalar(255, 0, 0));

    cv::Mat img_float;
    img.convertTo(img_float, CV_32FC3);

    cv::Mat img_normalized;
    cv::subtract(img_float, mean, img_normalized);

    // output
    cv::imwrite("1.jpg", img_normalized);
}

c++ output: 1.jpg is


----------------------------------------------------------------------------------------------------------------------------


import numpy as np
import caffe
import scipy.misc
from PIL import Image

transformer = caffe.io.Transformer({'data': (1, 3, 32, 32)})

transformer.set_transpose('data', (2,0,1))  # move image channels to outermost dimension
transformer.set_mean('data', np.array([255, 0, 0])) # subtract the dataset-mean value in each channel
transformer.set_raw_scale('data', 255)      # rescale from [0, 1] to [0, 255]
transformer.set_channel_swap('data', (2,1,0))  # swap channels from RGB to BGR

image = caffe.io.load_image('test.jpg')
transformed_image = transformer.preprocess('data', image)

# save result
t = transformed_image.transpose((1,2,0))
scipy.misc.imsave('2.jpg', t)

python output: 2.jpg is
Reply all
Reply to author
Forward
0 new messages