1. 程式人生 > >Python3下OpenCV影象格式轉換方法

Python3下OpenCV影象格式轉換方法

   OpenCV影象格式是BGR,和我們日常RGB影象顏色通道不一致,恰好相反。雖然顏色通道不一致,
但每個顏色通道的值是沒有問題的,如果解析出來,重新組合,就能轉換成RGB格式影象了。
    下面的程式碼,test_probelm是觀察效果。而method1、method2、method3提示了使用的三種方法。
__author__ = 'jcy'
import cv2
import matplotlib.pyplot as plt
class OpenCV_pyplot:
    def __init__(self,input_file="IMG_1043.jpg"):
        self.img=cv2.imread(input_file)
    def test_problem(self):
        cv2.imshow("OpenCV:BGR",self.img)
        cv2.waitKey(0)
        plt.figure(1)
        plt.imshow(self.img)
        plt.title("PyPlot:BGR")
        plt.show()
    def method1(self):
        plt.figure(2)
        plt.suptitle("method1")
        b, g, r = cv2.split(self.img)
        img2 = cv2.merge([r, g, b])
        plt.subplot(1, 2, 1)
        plt.imshow(self.img)
        plt.title("init:BGR")
        plt.subplot(1, 2, 2)
        plt.imshow(img2)
        plt.title('convert:RGB')
        plt.show()
    def method2(self):
        img2 = self.img[...,::-1]
        plt.figure(3)
        plt.suptitle("method2")
        plt.subplot(1, 2, 1)
        plt.imshow(self.img)
        plt.title("init:BGR")
        plt.subplot(1, 2, 2)
        plt.imshow(img2)
        plt.title('convert:RGB')
        plt.show()
    def method3(self):
        img2 = cv2.cvtColor(self.img, cv2.COLOR_BGR2RGB)
        plt.figure(4)
        plt.suptitle("method3")
        plt.subplot(1, 2, 1)
        plt.imshow(self.img)
        plt.title("init:BGR")
        plt.subplot(1, 2, 2)
        plt.imshow(img2)
        plt.title('convert:RGB')
        plt.show()
plot1=OpenCV_pyplot()
plot1.test_problem()
plot1.method1()
plot1.method2()
plot1.method3()