Android的直方图均衡化 [英] Android Histogram Equalization

查看:750
本文介绍了Android的直方图均衡化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Android Studio中下面的算法来平衡图像。

但它显示了在 getRaster 方法错误,亘古不承认它。此外的getRGB 也呈现出错误。

请告诉我,我错了。

我已经编辑了code照你说的,但它崩溃。

 进口java.io.IOException异常;
进口java.util.Arrays中;
进口的java.lang.Object;进口android.app.Activity;
进口android.app.Dialog;
进口android.app.ProgressDialog;
进口android.content.Context;
进口android.content.Intent;
进口android.content.pm.ActivityInfo;
进口android.database.Cursor;
进口android.graphics.Bitmap;
进口android.graphics.BitmapFactory;
进口android.graphics.Canvas;
进口android.graphics.Color;
进口android.graphics.Paint;
进口android.graphics.Paint.Style;
进口android.graphics.Path;
进口android.net.Uri;
进口android.os.AsyncTask;
进口android.os.Bundle;
进口android.provider.MediaStore;
进口android.util.DisplayMetrics;
进口android.util.Log;
进口android.view.View;
进口android.view.View.OnClickListener;
进口android.widget.Button;
进口android.widget.ImageView;
进口android.widget.LinearLayout;公共类webhist延伸活动{    位图双= NULL;
    布尔isColored;    观的LinearLayout;
    的LinearLayout view_color;    布尔标志;    私人INT SIZE = 256;
    //红,绿,蓝
    私人INT NUMBER_OF_COLOURS = 3;    公众最终诠释RED = 0;
    公众最终诠释绿色= 1;
    公众最终诠释BLUE = 2;    私人INT [] [] colourBins;
    私人挥发性布尔加载= FALSE;
    私人诠释MAXY;    私有静态最终诠释LDPI = 0;
    私有静态最终诠释MDPI = 1;
    私有静态最终诠释TVDPI = 2;
    私有静态最终诠释华电国际= 3;
    私有静态最终诠释XHDPI = 4;    浮偏移= 1;    @覆盖
    保护无效的onCreate(捆绑savedInstanceState){
        // TODO自动生成方法存根
        super.onCreate(savedInstanceState);        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);        的setContentView(R.layout.activity_webhist);
        DisplayMetrics指标=新DisplayMetrics();
        。getWindowManager()getDefaultDisplay()getMetrics(指标)。        如果(metrics.densityDpi == metrics.DENSITY_LOW)
            偏移量= 0.75f​​;
        否则,如果(metrics.densityDpi == metrics.DENSITY_MEDIUM)
            偏移量= 1F;
        否则,如果(metrics.densityDpi == metrics.DENSITY_TV)
            偏移量= 1.33f;
        否则,如果(metrics.densityDpi == metrics.DENSITY_HIGH)
            偏移量= 1.5F;
        否则,如果(metrics.densityDpi == metrics.DENSITY_XHIGH)
            偏移量= 2F;        Log.e(NIRAV,+偏移量);        colourBins =新INT [NUMBER_OF_COLOURS] [];        的for(int i = 0; I< NUMBER_OF_COLOURS;我++){
            colourBins [I] =新INT [SIZE]
        }        加载= FALSE;        键上传=(按钮)findViewById(R.id.upload);
        upload.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根                如果(标志){
                    view_color.removeAllViews();
                    view.removeAllViews();
                }
                它的意图=新意图(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(它,101);                标志=真实的;                / *
                 *观的LinearLayout =(的LinearLayout)findViewById(R.id.lyt);
                 * view.addView(新MyHistogram(getApplicationContext()));
                 * /
            }
        });        按钮直方图=(按钮)findViewById(R.id.hst_btn);
        histogram.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根
                如果(BI!= NULL){
                    isColored = FALSE;
                    鉴于=(的LinearLayout)findViewById(R.id.lyt);
                    view.addView(新MyHistogram(getApplicationContext(),BI));
                }
            }
        });
        按钮histogram_color =(按钮)findViewById(R.id.hst_color_btn);
        histogram_color.setOnClickListener(新OnClickListener(){            @覆盖
            公共无效的onClick(视图v){
                // TODO自动生成方法存根
                如果(BI!= NULL){
                    isColored = TRUE;
                    view_color =(的LinearLayout)findViewById(R.id.lyt_color);
                    view_color.addView(新MyHistogram(getApplicationContext(),
                            双));
                }
            }
        });    }    保护无效的onActivityResult(INT申请code,INT结果code,
                                    意向imageReturnedIntent){
        super.onActivityResult(要求code,结果code,imageReturnedIntent);        开关(要求code){            案例101:
                如果(结果code == RESULT_OK){
                    乌里selectedImage = imageReturnedIntent.getData();
                    字符串文件名= getRealPathFromURI(selectedImage);
                    BI = BitmapFactory.de codeFILE(文件名);
                / *
                ByteArrayOutputStream出=新ByteArrayOutputStream();
                bi.com preSS(Bitmap.Com pressFormat.JPEG,10出);
                BI = BitmapFactory.de codeStream(新ByteArrayInputStream进行(out.toByteArray())); * /                    如果(BI!= NULL)
                    {
                        尝试{
                            新MyAsync()执行();
                        }赶上(例外五){
                            // TODO自动生成catch块
                            e.printStackTrace();
                        }
                    }
                }
        }
    }    公共字符串getRealPathFromURI(URI contentUri){
        Log.e(TEST,GetRealPath:+ contentUri);        尝试{
            如果(contentUri.toString()。包括(视频)){
                的String [] = PROJ {MediaStore.Video.Media.DATA};
                光标光标= managedQuery(contentUri,凸出,NULL,NULL,NULL);
                INT与Column_Index =光标
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                cursor.moveToFirst();
                返回cursor.getString(Column_Index中);
            }其他{
                的String [] = PROJ {MediaStore.Images.Media.DATA};
                光标光标= managedQuery(contentUri,凸出,NULL,NULL,NULL);
                INT与Column_Index =光标
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                返回cursor.getString(Column_Index中);
            }
        }赶上(抛出:IllegalArgumentException五){
            // TODO自动生成catch块
            e.printStackTrace();
        }
        返回null;
    }    类MyAsync扩展的AsyncTask
    {
        @覆盖
        在preExecute保护无效(){
            // TODO自动生成方法存根
            super.on preExecute();
            的ShowDialog(0);
        }        @覆盖
        保护对象doInBackground(对象... PARAMS){
            // TODO自动生成方法存根            尝试{
                负荷(双向);
            }赶上(IOException异常五){
                // TODO自动生成catch块
                e.printStackTrace();
            }            返回null;
        }        @覆盖
        保护无效onPostExecute(对象结果){
            // TODO自动生成方法存根
            super.onPostExecute(结果);            ImageView的IMG =(ImageView的)findViewById(R.id.img);            img.setImageBitmap(BI);            ((按钮)findViewById(R.id.hst_btn))setVisibility(View.VISIBLE)。
            ((按钮)findViewById(R.id.hst_color_btn))setVisibility(View.VISIBLE)。            dismissDialog(0);
        }    }    公共无效负载(位图BI)抛出IOException        如果(BI!= NULL){
            //重置所有的垃圾箱
            的for(int i = 0; I< NUMBER_OF_COLOURS;我++){
                对于(INT J = 0; J<大小; J ++){
                    colourBins [I] [J] = 0;
                }
            }            为(中间体X = 0; X&下; bi.getWidth(); X ++){
                对于(INT Y = 0; Y< bi.getHeight(); Y ++){                    INT像素= bi.getPixel(X,Y);                    colourBins [红色] [Color.red(像素)] ++;
                    colourBins [绿色] [Color.green(像素)] ++;
                    colourBins [蓝] [Color.blue(像素)] ++;
                }
            }            MAXY = 0;            的for(int i = 0; I< NUMBER_OF_COLOURS;我++){
                对于(INT J = 0; J<大小; J ++){
                    如果(MAXY< colourBins [I] [J]){
                        MAXY = colourBins [I] [J]。
                    }
                }
            }
            加载=真实的;
        }其他{
            加载= FALSE;
        }
    }    类MyHistogram扩展视图{        公共MyHistogram(上下文的背景下,位图BI){
            超级(上下文);        }        @覆盖
        保护无效的onDraw(帆布油画){
            // TODO自动生成方法存根
            super.onDraw(画布);            如果(装入){
                canvas.drawColor(Color.GRAY);                Log.e(NIRAV,身高+的getHeight()+,宽度:
                        +的getWidth());                INT xInterval =(INT)((双)的getWidth()/((双)SIZE + 1));                的for(int i = 0; I< NUMBER_OF_COLOURS;我++){                    涂料wallpaint;                    wallpaint =新的油漆();
                    如果(isColored){
                        如果(我== RED){
                            wallpaint.setColor(Color.RED);
                        }否则如果(我==绿色){
                            wallpaint.setColor(Color.GREEN);
                        }否则如果(我== BLUE){
                            wallpaint.setColor(Color.BLUE);
                        }
                    }其他{
                        wallpaint.setColor(Color.WHITE);
                    }                    wallpaint.setStyle(Style.FILL);                    路径wallpath =新路径();
                    wallpath.reset();
                    wallpath.moveTo(0,的getHeight());
                    对于(INT J = 0; J<大小 - 1; J ++){
                        int值=(INT)(((双)colourBins [I] [J] /(双)MAXY)*(的getHeight()+ 100));
                        //如果(J == 0){
                        // wallpath.moveTo(J * xInterval *偏移的getHeight() - 值);
                        //}
                        //其他{
                        wallpath.lineTo(J * xInterval *偏移的getHeight() - 值);
                        //}
                    }
                    wallpath.lineTo(SIZE *偏移的getHeight());
                    canvas.drawPath(wallpath,wallpaint);
                }            }        }
    }
公共无效灰色(查看视图1){
        操作= Bitmap.createBitmap(bi.getWidth()
                bi.getHeight(),bi.getConfig());
        histEqualize(BI,操作);
    }
    公众诠释[] CalculateHist(位图BI){
        时int k;
        //数组重新presents像素的intecity值
        INT水平[] =新INT [256];
        的for(int i = 0; I< bi.getWidth();我++){
            对于(INT J = 0; J< bi.getHeight(); J ++){
                INT像素= bi.getPixel(I,J);
                //如果相同的像素增加出现
                [Color.red(象素)] +的水平;
            }
        }
        //返回数组直方图
        返回的水平;
    }
    公共无效histEqualize(双位图,位图bi_out){
        //调用CalculateHist方法来获取直方图
        INT [] H = CalculateHist(BI);
        //计算像素总数
        INT质量= bi.getWidth()* bi.getHeight();
        INT K = 0;
        长总和= 0;        //计算比例因子
        浮规模=(浮点)255.0 /质谱;
        // calculte CDF
        为(中间体X = 0; X&下; h.length; X ++){
            总和+ = H [X];
            int值=(INT)(*规模总和);
            如果(价值> 255){
                值= 255;
            }
            H [X] =价值;
        }
        的for(int i = 0; I< bi.getWidth();我++){
            对于(INT J = 0; J< bi.getHeight(); J ++){
                INT像素= bi.getPixel(I,J);
                //设置新值
                K为H [Color.red(象素)];
                INT RGB = Color.rgb(K,K,K);
                bi_out.setPixel(I,J,RGB);
            }
        }
    }
    // INT像素[]; < - 删除此
    @覆盖
    保护对话框onCreateDialog(INT ID){
        ProgressDialog dataLoadProgress =新ProgressDialog(本);
        dataLoadProgress.setMessage(正在加载...);
        dataLoadProgress.setIndeterminate(真);
        dataLoadProgress.setCancelable(假);
        dataLoadProgress.setProgressStyle(android.R.attr.progressBarStyleLarge);
        返回dataLoadProgress;    }}

这是我的layout.xml文件

 <滚动型的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
    机器人:layout_width =match_parent
    机器人:layout_height =match_parent>
    < LinearLayout中的xmlns:机器人=htt​​p://schemas.android.com/apk/res/android
        的xmlns:工具=htt​​p://schemas.android.com/tool​​s
        机器人:layout_width =match_parent
        机器人:layout_height =match_parent
        机器人:方向=垂直
        机器人:背景=@机器人:彩色/ holo_blue_bright>        <的LinearLayout
            机器人:layout_width =WRAP_CONTENT
            机器人:layout_height =FILL_PARENT
            机器人:比重=中心
            机器人:方向=垂直
            机器人:背景=@机器人:彩色/白>            <的LinearLayout
                机器人:ID =@ + ID / LYT
                机器人:layout_width =383dp
                机器人:layout_height =140dp
                机器人:方向=垂直>
            < / LinearLayout中>            <按钮
                机器人:ID =@ + ID / hst_btn
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:文本=显示直方图
                机器人:知名度=隐形/>            <按钮
                机器人:ID =@ + ID / hst_color_btn
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:文本=显示颜色直方图
                机器人:知名度=隐形/>            <的LinearLayout
                机器人:ID =@ + ID / lyt_color
                机器人:layout_width =match_parent
                机器人:layout_height =140dp
                机器人:方向=垂直>
            < / LinearLayout中>
        < / LinearLayout中>        < RelativeLayout的
            机器人:layout_width =match_parent
            机器人:layout_height =267dp>            < ImageView的
                机器人:ID =@ + ID / IMG
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:scaleType =fitCenter
                 />            <按钮的android:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:文字=选择图片
                机器人:ID =@ + ID /上传
                机器人:layout_margin =20dp
                机器人:背景=@机器人:彩色/白
                机器人:文字颜色=@机器人:彩色/黑白/>            <按钮
                机器人:layout_width =WRAP_CONTENT
                机器人:layout_height =WRAP_CONTENT
                机器人:文字=Equalised形象
                安卓的onClick =灰色
                机器人:ID =@ + ID /按钮
                机器人:layout_alignTop =@ + ID /上传
                机器人:layout_alignParentRight =真
                机器人:layout_alignParentEnd =真
                机器人:layout_marginRight =38dp
                机器人:layout_marginEnd =38dp/>            < ImageView的
                机器人:ID =@ + ID / ImageView的
                机器人:layout_width =FILL_PARENT
                机器人:layout_height =FILL_PARENT
                机器人:scaleType =fitCenter
                机器人:layout_alignParentEnd =FALSE/>        < / RelativeLayout的>    < / LinearLayout中>
< /滚动型>


解决方案

有在Android没有 getRaster()方法位图类。相反,你可以调用与getPixel()位图直接。该函数返回一个整数ARGB值,可以分解到各个组成部分:

  INT像素= bi.getPixel(I,J);
//如果相同的像素增加出现
[Color.red(象素)] +的水平;

您可以设置一个像素是这样的:

  INT RGB = Color.rgb(K,K,K);
 bi.setPixel(I,J,RGB);

I am using the following algorithm in Android Studio to equalize an image.

But it shows error in getRaster method and doesnot recognise it. Also getRGB is also showing errors.

Please tell me where I am going wrong.

I have edited the code as you said but it crashes.

    import java.io.IOException;
import java.util.Arrays;
import java.lang.Object;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;



public class webhist extends Activity {

    Bitmap bi = null;


    boolean isColored;

    LinearLayout view;
    LinearLayout view_color;

    boolean flag;

    private int SIZE = 256;
    // Red, Green, Blue
    private int NUMBER_OF_COLOURS = 3;

    public final int RED = 0;
    public final int GREEN = 1;
    public final int BLUE = 2;

    private int[][] colourBins;
    private volatile boolean loaded = false;
    private int maxY;

    private static final int LDPI = 0;
    private static final int MDPI = 1;
    private static final int TVDPI = 2;
    private static final int HDPI = 3;
    private static final int XHDPI = 4;

    float offset = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

        setContentView(R.layout.activity_webhist);


        DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);

        if(metrics.densityDpi==metrics.DENSITY_LOW)
            offset = 0.75f;
        else if(metrics.densityDpi==metrics.DENSITY_MEDIUM)
            offset = 1f;
        else if(metrics.densityDpi==metrics.DENSITY_TV)
            offset = 1.33f;
        else if(metrics.densityDpi==metrics.DENSITY_HIGH)
            offset = 1.5f;
        else if(metrics.densityDpi==metrics.DENSITY_XHIGH)
            offset = 2f;

        Log.e("NIRAV",""+offset);

        colourBins = new int[NUMBER_OF_COLOURS][];

        for (int i = 0; i < NUMBER_OF_COLOURS; i++) {
            colourBins[i] = new int[SIZE];
        }

        loaded = false;

        Button upload = (Button) findViewById(R.id.upload);
        upload.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                if (flag) {
                    view_color.removeAllViews();
                    view.removeAllViews();
                }
                Intent it = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(it, 101);

                flag = true;

                /*
                 * LinearLayout view = (LinearLayout) findViewById(R.id.lyt);
                 * view.addView(new MyHistogram(getApplicationContext()));
                 */
            }
        });

        Button histogram = (Button) findViewById(R.id.hst_btn);
        histogram.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (bi != null) {
                    isColored = false;
                    view = (LinearLayout) findViewById(R.id.lyt);
                    view.addView(new MyHistogram(getApplicationContext(), bi));
                }
            }
        });
        Button histogram_color = (Button) findViewById(R.id.hst_color_btn);
        histogram_color.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                if (bi != null) {
                    isColored = true;
                    view_color = (LinearLayout) findViewById(R.id.lyt_color);
                    view_color.addView(new MyHistogram(getApplicationContext(),
                            bi));
                }
            }
        });

    }

    protected void onActivityResult(int requestCode, int resultCode,
                                    Intent imageReturnedIntent) {
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);

        switch (requestCode) {

            case 101:
                if (resultCode == RESULT_OK) {
                    Uri selectedImage = imageReturnedIntent.getData();
                    String filename = getRealPathFromURI(selectedImage);
                    bi = BitmapFactory.decodeFile(filename);
                /*
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                bi.compress(Bitmap.CompressFormat.JPEG,10,out);
                bi = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));*/

                    if(bi!=null)
                    {
                        try {
                            new MyAsync().execute();
                        } catch (Exception e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }
                }
        }
    }

    public String getRealPathFromURI(Uri contentUri) {
        Log.e("TEST", "GetRealPath : " + contentUri);

        try {
            if (contentUri.toString().contains("video")) {
                String[] proj = { MediaStore.Video.Media.DATA };
                Cursor cursor = managedQuery(contentUri, proj, null, null, null);
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            } else {
                String[] proj = { MediaStore.Images.Media.DATA };
                Cursor cursor = managedQuery(contentUri, proj, null, null, null);
                int column_index = cursor
                        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
                cursor.moveToFirst();
                return cursor.getString(column_index);
            }
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    class MyAsync extends AsyncTask
    {
        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            showDialog(0);
        }

        @Override
        protected Object doInBackground(Object... params) {
            // TODO Auto-generated method stub

            try {
                load(bi);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Object result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);

            ImageView img = (ImageView) findViewById(R.id.img);

            img.setImageBitmap(bi);

            ((Button) findViewById(R.id.hst_btn)).setVisibility(View.VISIBLE);
            ((Button) findViewById(R.id.hst_color_btn)).setVisibility(View.VISIBLE);

            dismissDialog(0);
        }

    }

    public void load(Bitmap bi) throws IOException {

        if (bi != null) {
            // Reset all the bins
            for (int i = 0; i < NUMBER_OF_COLOURS; i++) {
                for (int j = 0; j < SIZE; j++) {
                    colourBins[i][j] = 0;
                }
            }

            for (int x = 0; x < bi.getWidth(); x++) {
                for (int y = 0; y < bi.getHeight(); y++) {

                    int pixel = bi.getPixel(x, y);

                    colourBins[RED][Color.red(pixel)]++;
                    colourBins[GREEN][Color.green(pixel)]++;
                    colourBins[BLUE][Color.blue(pixel)]++;
                }
            }

            maxY = 0;

            for (int i = 0; i < NUMBER_OF_COLOURS; i++) {
                for (int j = 0; j < SIZE; j++) {
                    if (maxY < colourBins[i][j]) {
                        maxY = colourBins[i][j];
                    }
                }
            }
            loaded = true;
        } else {
            loaded = false;
        }
    }

    class MyHistogram extends View {

        public MyHistogram(Context context, Bitmap bi) {
            super(context);

        }

        @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);

            if (loaded) {
                canvas.drawColor(Color.GRAY);

                Log.e("NIRAV", "Height : " + getHeight() + ", Width : "
                        + getWidth());

                int xInterval = (int) ((double) getWidth() / ((double) SIZE + 1));

                for (int i = 0; i < NUMBER_OF_COLOURS; i++) {

                    Paint wallpaint;

                    wallpaint = new Paint();
                    if (isColored) {
                        if (i == RED) {
                            wallpaint.setColor(Color.RED);
                        } else if (i == GREEN) {
                            wallpaint.setColor(Color.GREEN);
                        } else if (i == BLUE) {
                            wallpaint.setColor(Color.BLUE);
                        }
                    } else {
                        wallpaint.setColor(Color.WHITE);
                    }

                    wallpaint.setStyle(Style.FILL);

                    Path wallpath = new Path();
                    wallpath.reset();
                    wallpath.moveTo(0, getHeight());
                    for (int j = 0; j < SIZE - 1; j++) {
                        int value = (int) (((double) colourBins[i][j] / (double) maxY) * (getHeight()+100));


                        //if(j==0) {
                        //   wallpath.moveTo(j * xInterval* offset, getHeight() - value);
                        //}
                        // else {
                        wallpath.lineTo(j * xInterval * offset, getHeight() - value);
                        // }
                    }
                    wallpath.lineTo(SIZE * offset, getHeight());
                    canvas.drawPath(wallpath, wallpaint);
                }

            }

        }
    }
public void gray(View view1) {
        operation = Bitmap.createBitmap(bi.getWidth(),
                bi.getHeight(), bi.getConfig());
        histEqualize(bi,operation);
    }


    public int[] CalculateHist(Bitmap bi) {
        int k;
        //array represents the intecity values of the pixels
        int levels[] = new int[256];
        for (int i = 0; i < bi.getWidth(); i++) {
            for (int j = 0; j < bi.getHeight(); j++) {
                int pixel = bi.getPixel(i, j);
                //increase if same pixel appears
                levels[Color.red(pixel)]++;
            }
        }
        //return the histogram array
        return levels;
    }
    public void histEqualize(Bitmap bi, Bitmap bi_out) {
        //call CalculateHist method to get the histogram
        int[] h = CalculateHist(bi);
        //calculate total number of pixel
        int mass = bi.getWidth() * bi.getHeight();
        int k = 0;
        long sum = 0;

        //calculate the scale factor
        float scale = (float) 255.0 / mass;
        //calculte cdf
        for (int x = 0; x < h.length; x++) {
            sum += h[x];
            int value = (int) (scale * sum);
            if (value > 255) {
                value = 255;
            }
            h[x] = value;
        }
        for (int i = 0; i < bi.getWidth(); i++) {
            for (int j = 0; j < bi.getHeight(); j++) {
                int pixel = bi.getPixel(i, j);
                //set the new value
                k = h[Color.red(pixel)];
                int rgb = Color.rgb(k, k, k);
                bi_out.setPixel(i, j, rgb);
            }
        }
    }
    // int pixel[]; <-- remove this
    @Override
    protected Dialog onCreateDialog(int id) {
        ProgressDialog dataLoadProgress = new ProgressDialog(this);
        dataLoadProgress.setMessage("Loading...");
        dataLoadProgress.setIndeterminate(true);
        dataLoadProgress.setCancelable(false);
        dataLoadProgress.setProgressStyle(android.R.attr.progressBarStyleLarge);
        return dataLoadProgress;

    }

}

This is My layout.xml file

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:background="@android:color/holo_blue_bright">

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:gravity="center"
            android:orientation="vertical"
            android:background="@android:color/white">

            <LinearLayout
                android:id="@+id/lyt"
                android:layout_width="383dp"
                android:layout_height="140dp"
                android:orientation="vertical" >
            </LinearLayout>

            <Button
                android:id="@+id/hst_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Show Histogram"
                android:visibility="invisible"/>

            <Button
                android:id="@+id/hst_color_btn"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Show Color Histogram"
                android:visibility="invisible"/>

            <LinearLayout
                android:id="@+id/lyt_color"
                android:layout_width="match_parent"
                android:layout_height="140dp"
                android:orientation="vertical" >
            </LinearLayout>
        </LinearLayout>

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="267dp" >

            <ImageView
                android:id="@+id/img"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitCenter"
                 />

            <Button android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Select Image"
                android:id="@+id/upload"
                android:layout_margin="20dp"
                android:background="@android:color/white"
                android:textColor="@android:color/black"/>

            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Equalised image"
                android:onClick="gray"
                android:id="@+id/button"
                android:layout_alignTop="@+id/upload"
                android:layout_alignParentRight="true"
                android:layout_alignParentEnd="true"
                android:layout_marginRight="38dp"
                android:layout_marginEnd="38dp" />

            <ImageView
                android:id="@+id/imageView"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scaleType="fitCenter"
                android:layout_alignParentEnd="false" />

        </RelativeLayout>

    </LinearLayout>
</ScrollView>

解决方案

There is no getRaster() method in the Android Bitmap class. Instead you can call getPixel() on the Bitmap directly. The function returns an integer ARGB value, which you can separate into its various components:

int pixel = bi.getPixel(i, j);
//increase if same pixel appears
levels[Color.red(pixel)]++;

You can set a pixel like this:

 int rgb = Color.rgb(k, k, k);
 bi.setPixel(i, j, rgb);

这篇关于Android的直方图均衡化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆