简体   繁体   中英

OpenCv inversion: BGR to HSV then back to BGR - shouldn't I get the same image?

For example, when I run this:

import cv2
import numpy as np
from collections import Counter

# load image, calculate some basic stats
path = 'path/to/my/image.png'
bgr_img = cv2.imread(path)
h, w, c = bgr_img.shape
print("There are %d entries in this %d channel image" % (h*w*c, c))

# convert and then invert, we should get the same image
bgr_img2 = cv2.cvtColor(cv2.cvtColor(bgr_img, cv2.COLOR_BGR2HSV), cv2.COLOR_HSV2BGR)
print("all entries match: %s" % np.all(bgr_img == bgr_img2))

# hmm, we don't. let's see where the differences are
mismatches = np.where(bgr_img != bgr_img2)
print("there are %d mismatched entries" % len(mismatches[0]))
print("mismatches are along the following channels: %s" % Counter(mismatches[2]))

# ok, clearly lots of them. maybe they're all just off by 1 or 2?
mm = zip(mismatches[0], mismatches[1], mismatches[2])
differences = []
for x, y, c in mm:
    diff = bgr_img[x, y, c] - bgr_img2[x, y, c]
    differences.append(diff)

print(differences)

I get the following output:

There are 1228800 entries in this 3 channel image
all entries match: False
there are 524511 mismatched entries
mismatches are along the following channels: Counter({1: 270572, 0: 253939})
[1, 1, 1, 254, 1, 254, 1, 3, 1, 3, 1, 3, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 254, 1, 3, 1, 3, 1, 3, 1, 254, 1, 254, 254, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, ...]

I see a couple possibilities. First is that BGR -> HSV conversion isn't strictly invertible. Other is that I'm using OpenCV incorrectly. Which is it?

You should get pretty much the same image, but not, except in edge cases, identical bits. BGR to HSV (and back) involve a transformation between spaces that don't have identical representations for all values in the other space. Small rounding errors will creep in.

See the note in https://docs.opencv.org/3.4/df/d9d/tutorial_py_colorspaces.html about the Hue range being [0, 179]. If you think about it, that implies information loss when converting from BGR (or RGB). You can't get those bits back reliably.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM