将openCV查找表(LUT)应用于图像

时间:2017-02-10 21:50:54

标签: python opencv lookup-tables

我想在图片上应用自定义颜色查找表 LUT )。

我查看了openCV LUT Api,但我似乎无法做到正确。

#!/bin/bash
# -*- coding: utf-8 -*-

import os
import numpy as np
import cv2

b_max = 230
g_max = 220
r_max = 250

identity = np.arange(256, dtype = np.dtype('uint8'))

b_channel = np.arange(b_max, dtype = np.dtype('uint8'))
b_channel = np.append(b_channel, (256-b_max)*[b_max])
g_channel = np.arange(g_max, dtype = np.dtype('uint8'))
g_channel = np.append(g_channel, (256-g_max)*[g_max])
r_channel = np.arange(r_max, dtype = np.dtype('uint8'))
r_channel = np.append(r_channel, (256-r_max)*[r_max])

if 256 != b_channel.size or 256 != g_channel.size or 256 != r_channel.size:
    print "size of arrays don't match!"

lut = np.dstack((identity, identity, b_channel, g_channel, r_channel))

# Load the image
img = cv2.imread('input.jpg',cv2.IMREAD_COLOR)
dstImage = cv2.LUT(img, lut)
cv2.imwrite('output.jpg', dstImage)

我收到以下错误:

OpenCV Error: Assertion failed ((lutcn == cn || lutcn == 1) && _lut.total() == 256 && _lut.isContinuous() && (depth == CV_8U || depth == CV_8S)) in cv::LUT, file C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\core\src\convert.cpp, line 5690
Traceback (most recent call last):
  File "ApplyCLUT.py", line 33, in <module>
    dstImage = cv2.LUT(img, lut)
cv2.error: C:\build\master_winpack-bindings-win32-vc14-static\opencv\modules\core\src\convert.cpp:5690: error: (-215) (lutcn == cn || lutcn == 1) && _lut.total() == 256 && _lut.isContinuous() && (depth == CV_8U || depth == CV_8S) in function cv::LUT

修改: 改为这一行:

lut = np.dstack( (b_channel, g_channel, r_channel) )

它会起作用!

1 个答案:

答案 0 :(得分:4)

以下是构建LUT的示例:

img[:,:,2] = 0

请注意,将红色通道归零有更简单直接的方法:

dstImage = cv2.LUT(img, lut)

同样调用LUT函数应如下所示:

b_max = 20
img[img[:,:,0] > b_max, 0] = b_max;

将大于b_max的蓝色值设置为b_max:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.syntax.bottomtabs.MainActivity">
<RelativeLayout 
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginTop="10dp"
    android:layout_marginBottom="10dp"
    android:layout_marginLeft="10dp"
    android:layout_marginRight="10dp"
    android:id="@+id/output">
</RelativeLayout>

<com.roughike.bottombar.BottomBar
    android:id="@+id/bottomBar"
    android:layout_width="match_parent"
    android:layout_height="70dp"
    android:layout_alignParentBottom="true"
    app:bb_tabXmlResource="@xml/bottombar_tabs_three" />
</RelativeLayout>