1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 18package android.filterpacks.imageproc; 19 20import android.filterfw.core.Filter; 21import android.filterfw.core.FilterContext; 22import android.filterfw.core.Frame; 23import android.filterfw.core.FrameFormat; 24import android.filterfw.core.GenerateFieldPort; 25import android.filterfw.core.KeyValueMap; 26import android.filterfw.core.MutableFrameFormat; 27import android.filterfw.core.NativeProgram; 28import android.filterfw.core.NativeFrame; 29import android.filterfw.core.Program; 30import android.filterfw.core.ShaderProgram; 31import android.filterfw.format.ImageFormat; 32 33import android.util.Log; 34 35import java.lang.reflect.Field; 36 37/** 38 * @hide 39 */ 40public class ToGrayFilter extends SimpleImageFilter { 41 42 @GenerateFieldPort(name = "invertSource", hasDefault = true) 43 private boolean mInvertSource = false; 44 45 @GenerateFieldPort(name = "tile_size", hasDefault = true) 46 private int mTileSize = 640; 47 48 private MutableFrameFormat mOutputFormat; 49 50 private static final String mColorToGray4Shader = 51 "precision mediump float;\n" + 52 "uniform sampler2D tex_sampler_0;\n" + 53 "varying vec2 v_texcoord;\n" + 54 "void main() {\n" + 55 " vec4 color = texture2D(tex_sampler_0, v_texcoord);\n" + 56 " float y = dot(color, vec4(0.299, 0.587, 0.114, 0));\n" + 57 " gl_FragColor = vec4(y, y, y, color.a);\n" + 58 "}\n"; 59 60 public ToGrayFilter(String name) { 61 super(name, null); 62 } 63 64 @Override 65 public void setupPorts() { 66 addMaskedInputPort("image", ImageFormat.create(ImageFormat.COLORSPACE_RGBA, 67 FrameFormat.TARGET_GPU)); 68 addOutputBasedOnInput("image", "image"); 69 } 70 71 @Override 72 protected Program getNativeProgram(FilterContext context) { 73 throw new RuntimeException("Native toGray not implemented yet!"); 74 } 75 76 @Override 77 protected Program getShaderProgram(FilterContext context) { 78 int inputChannels = getInputFormat("image").getBytesPerSample(); 79 if (inputChannels != 4) { 80 throw new RuntimeException("Unsupported GL input channels: " + 81 inputChannels + "! Channels must be 4!"); 82 } 83 ShaderProgram program = new ShaderProgram(context, mColorToGray4Shader); 84 program.setMaximumTileSize(mTileSize); 85 if (mInvertSource) 86 program.setSourceRect(0.0f, 1.0f, 1.0f, -1.0f); 87 return program; 88 } 89 90} 91