簡體   English   中英

OpenCv反轉:將BGR轉換為HSV,然后再返回BGR-我是否應該獲得相同的圖像?

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

例如,當我運行此命令時:

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)

我得到以下輸出:

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, ...]

我看到了幾種可能性。 首先是BGR-> HSV轉換不是嚴格可逆的。 其他是我使用的OpenCV不正確。 哪有

您應該獲得幾乎相同的圖像,但除了邊緣情況外,不會獲得相同的位。 從BGR到HSV(以及向后)涉及到空間之間的轉換,這些空間對於其他空間中的所有值沒有相同的表示形式。 小數舍入誤差將蔓延。

請參閱https://docs.opencv.org/3.4/df/d9d/tutorial_py_colorspaces.html中有關色調范圍[0,179]的注釋。 如果您考慮一下,這意味着從BGR(或RGB)轉換時會丟失信息。 您無法可靠地收回這些位。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM