I've noticed that the matrix output of an image from Python cv2, has different values for the same pixel read by Java ImageIO. What is the cause of this and how can we get an unanimous value in Java without usage of Java-OpenCV dependency. Test code and bus.jpg for comparison:
import cv2
if __name__ == '__main__':
path = 'bus.jpg'
img0 = cv2.imread(path) # BGR
print(img0[0][0][0]) # 122 output
VS
final BufferedImage image = ImageIO.read(new File("bus.jpg"));
var rgb = image.getRGB(0, 0);
var red = (rgb >> 16) & 0xFF;
var green = (rgb >> 8) & 0xFF;
var blue = rgb & 0xFF;
System.out.println(blue); // 118 output
CodePudding user response:
It's because OpenCV does not process an ICC profile embedded in that JPEG image.
You can either convert colors with an image editing tool such as GIMP, or convert with Python using a library such as Pillow.
This is an example of the latter.
import io
import numpy as np
import cv2
import PIL.Image
import PIL.ImageCms
img = PIL.Image.open('bus.jpg')
img_profile = PIL.ImageCms.ImageCmsProfile(io.BytesIO(img.info.get('icc_profile')))
rgb_profile = PIL.ImageCms.createProfile('sRGB')
trans = PIL.ImageCms.buildTransform(img_profile, rgb_profile, 'RGB', 'RGB')
img = PIL.ImageCms.applyTransform(img, trans)
cv_img = cv2.cvtColor(np.array(img), cv2.COLOR_RGB2BGR)