Python OpenCV和MATLAB之间的不同颜色结果

时间:2016-10-15 11:52:36

标签: python matlab opencv image-processing ipython

我要将RGB图像转换为YIQ图像,反之亦然。问题是Python给我一个奇怪的图像,而MATLAB显示正确的图像。我花了几个小时来弄清楚什么是错的,但我仍然不知道。

我将Python 3.5.2与OpenCV 3.1.0和MATLAB R2016a一起使用。

RGB2YIQ的Python代码:

import cv2 as cv
import numpy as np

def rgb2yiq(img):
   row, col, ch = img.shape
   Y = np.zeros((row,col))
   I = np.zeros((row,col))
   Q = np.zeros((row,col))
   for i in range(row):
      for j in range(col):
         Y[i,j] = 0.299 * img[i,j,2] + 0.587 * img[i,j,1] + 0.114 * img[i,j,0]
         I[i,j] = 0.596 * img[i,j,2] - 0.274 * img[i,j,1] - 0.322 * img[i,j,0]
         Q[i,j] = 0.211 * img[i,j,2] - 0.523 * img[i,j,1] + 0.312 * img[i,j,0]
   yiq = cv.merge((Y,I,Q))
   return yiq.astype(np.uint8)

def main():
   img = cv.imread("C:/Users/Kadek/Documents/MATLAB/peppers.jpg")
   img = rgb2yiq(img)
   cv.imwrite("YIQ.jpg",img)
   cv.namedWindow('Image', cv.WINDOW_NORMAL)
   cv.imshow('Image', img)
   cv.waitKey(0)
   cv.destroyAllWindows()

main()

RGB2YIQ的MATLAB代码:

img = imread('peppers.jpg');
[row col ch] = size(img);

for x=1:row
  for y=1:col
      Y(x,y) = 0.299 * img(x,y,1) + 0.587 * img(x,y,2) + 0.114 * img(x,y,3);
      I(x,y) = 0.596 * img(x,y,1) - 0.274 * img(x,y,2) - 0.322 * img(x,y,3);
      Q(x,y) = 0.211 * img(x,y,1) - 0.523 * img(x,y,2) + 0.312 * img(x,y,3);
  end
end

yiq(:,:,1) = Y;
yiq(:,:,2) = I;
yiq(:,:,3) = Q;

figure, imshow(yiq);

Result for RGB2YIQ

YIQ2RGB的Python代码:

import cv2 as cv
import numpy as np

def yiq2rgb(img):
   row, col, ch = img.shape
   r = np.zeros((row,col))
   g = np.zeros((row,col))
   b = np.zeros((row,col))
   for i in range(row):
      for j in range(col):
         r[i,j] = img[i,j,0] * 1.0 + img[i,j,1] * 0.9562 + img[i,j,2] * 0.6214
         g[i,j] = img[i,j,0] * 1.0 - img[i,j,1] * 0.2727 - img[i,j,2] * 0.6468
         b[i,j] = img[i,j,0] * 1.0 - img[i,j,1] * 1.1037 + img[i,j,2] * 1.7006
   rgb = cv.merge((b,g,r))
   return rgb.astype(np.uint8)

def main():
   img = cv.imread("YIQ.jpg")
   img = yiq2rgb(img)
   cv.imwrite("test.jpg",img)
   cv.namedWindow('Image', cv.WINDOW_NORMAL)
   cv.imshow('Image', img)
   cv.waitKey(0)
   cv.destroyAllWindows()

main()

YIQ2RGB的MATLAB代码:

img = imread('YIQ.jpg');
[row col ch] = size(img);

for x=1:row
  for y=1:col
      R(x,y) = 1.0 * img(x,y,1) + 0.9562 * img(x,y,2) + 0.6214 * img(x,y,3);
      G(x,y) = 1.0 * img(x,y,1) - 0.2727 * img(x,y,2) - 0.6468 * img(x,y,3);
      B(x,y) = 1.0 * img(x,y,1) - 1.1037 * img(x,y,2) + 1.7006 * img(x,y,3);
  end
end

rgb(:,:,1) = R;
rgb(:,:,2) = G;
rgb(:,:,3) = B;

imwrite(rgb,'YIQ2RGB.jpg');

figure, imshow(rgb);

Result for YIQ2RGB

有人说我曾经在操作它之前将图像转换为float64。已经尝试过,但没有改变。 我还使用astype(np.uint8)将float64转换为uint8以避免[0..255]之外的值。在MATLAB中没有这样的问题。

1 个答案:

答案 0 :(得分:0)

由于某些计算组件超出范围[0,255],您显然会遇到饱和问题。钳制值或调整增益。

然后似乎在某处交换组件。