Python中是否有OpenCV的颜色映射表?

7
我知道 Matlab, matplotlib style colormap in OpenCV。文档解释了它在C++中的用法。我想知道是否存在使用cv2的python选项。我搜索了很多,但没有找到答案。我知道可以使用matplotlib的colormap选项,但如果cv2提供这样的选项,我就可以省去将matplotlib colormaps转换为opencv图像的麻烦。这很笨拙。我需要它来完成我的项目。
4个回答

15

针对OpenCV 2.4.11版本,applyColorMap在Python中也可以使用(尽管2.4.11文档仍只列出了C++的使用):

import cv2
im = cv2.imread('test.jpg', cv2.IMREAD_GRAYSCALE)
imC = cv2.applyColorMap(im, cv2.COLORMAP_JET)

参见这个Stack Overflow答案


2

很遗憾,看起来它还没有进入Python API。但你可以查看modules/contrib/src/colormap.cpp中的实现,比如jetmap只是一个查找表,你可以直接使用。


我真的希望它已经实现了......好吧,我会开始着手处理。谢谢。 - Yash

1

遗憾的是,OpenCV没有任何colorMap,但您可以编写一个。并不难。

class ColorMap:
    startcolor = ()
    endcolor = ()
    startmap = 0
    endmap = 0
    colordistance = 0
    valuerange = 0
    ratios = []    

    def __init__(self, startcolor, endcolor, startmap, endmap):
        self.startcolor = np.array(startcolor)
        self.endcolor = np.array(endcolor)
        self.startmap = float(startmap)
        self.endmap = float(endmap)
        self.valuerange = float(endmap - startmap)
        self.ratios = (self.endcolor - self.startcolor) / self.valuerange

    def __getitem__(self, value):
        color = tuple(self.startcolor + (self.ratios * (value - self.startmap)))
        return (int(color[0]), int(color[1]), int(color[2]))

你能举个例子解释一下这应该如何运作吗? - Ivan

0

之前尝试在Python中使用applyColorMap的示例无法正常工作。 想要分享一下。 对于我的“臃肿”表示歉意。 如果您的视频摄像头未被识别或者有多个摄像头,请将“0”替换为“1”。

import cv2
import numpy as np

frameWidth = 940
frameHeight = 680
cap = cv2.VideoCapture(0)
cap.set(3, frameWidth)  # 3=width, 4=height
cap.set(4, frameHeight)

while True:
    success, imgColor, = cap.read()
    img = cv2.resize(imgColor, (frameWidth, frameHeight))  # if want to resize frame
    
    # ORIG IMG
    cv2.moveWindow("img", 0, 0)  # relocate shift reposition move so frame is at top left corner of monitor
    cv2.imshow("img", img)
    
    # COLOR ENHANCED
    cv2.moveWindow("imgColor", frameWidth, 0)  # relocate shift reposition move to side by side
    # COLORMAP_AUTUMN = 0
    # COLORMAP_BONE = 1
    # COLORMAP_COOL = 8
    # COLORMAP_HOT = 11
    # COLORMAP_HSV = 9
    # COLORMAP_JET = 2
    # COLORMAP_OCEAN = 5
    # COLORMAP_PINK = 10
    # COLORMAP_RAINBOW = 4
    # COLORMAP_SPRING = 7
    # COLORMAP_SUMMER = 6
    # COLORMAP_WINTER = 3
    cv2.imshow("imgColor", cv2.applyColorMap(imgColor, 3))  # change the last variable in here

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接