我知道OpenCV中的Matlab、matplotlib风格的颜色映射。文档解释了它在C++中的用法。我想知道使用cv2的python是否也存在这样的选项。我在谷歌上搜索了很多却一无所获。我知道我可以使用matplotlib的颜色映射选项,但如果cv2提供这样的选项,我可以消除将matplotllib颜色映射转换为opencv图像的开销。它很笨拙。我的项目需要它。
对于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)
另请参阅此堆栈溢出答案。
遗憾的是,它看起来还没有进入python api。但是您可以查看modules/contrib/src/colormap.cpp中的实现,例如,jetmap只是一个查找表,您可以直接窃取它
遗憾的是,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]))
无法在Python中使用前面的applyColorMap示例。我想我也一样。我为"胖"道歉。如果你的摄像机没有被识别,或者有多个摄像机,用"1"代替"0"
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