gpt4 book ai didi

android - 如何在 Android 中生成图像直方图?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:49:58 27 4
gpt4 key购买 nike

我尝试使用以下代码生成图像的直方图,

package com.example.viewfinderee368;

import java.nio.ByteBuffer;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

@SuppressLint("DrawAllocation")
public class HistogramDemo extends Activity {

Bitmap mainImage;
Bitmap histroImage;

ImageView mainImageView;
LinearLayout histroImageView;

private DrawOnTop mDrawOnTop;

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

mainImageView = (ImageView) findViewById(R.id.img);
histroImageView = (LinearLayout) findViewById(R.id.histroImg);

mainImage = ((BitmapDrawable) mainImageView.getDrawable()).getBitmap();
histroImage = Bitmap.createBitmap(mainImage);

mDrawOnTop = new DrawOnTop(this);

mDrawOnTop.mImageWidth = mainImage.getWidth();
mDrawOnTop.mImageHeight = mainImage.getHeight();
mDrawOnTop.mBitmap = Bitmap.createBitmap(mDrawOnTop.mImageWidth,
mDrawOnTop.mImageHeight, Bitmap.Config.RGB_565);
mDrawOnTop.mRGBData = new int[mDrawOnTop.mImageWidth * mDrawOnTop.mImageHeight];

int bytes = mainImage.getByteCount();
//or we can calculate bytes this way. Use a different value than 4 if you don't use 32bit images.
//int bytes = b.getWidth()*b.getHeight()*4;

ByteBuffer buffer = ByteBuffer.allocate(bytes); //Create a new buffer
mainImage.copyPixelsToBuffer(buffer); //Move the byte data to the buffer


byte[] array = buffer.array();
mDrawOnTop.mYUVData =array;

System.arraycopy(array, 0, mDrawOnTop.mYUVData, 0, array.length);
// mDrawOnTop.invalidate();
histroImageView.addView(mDrawOnTop);

}

class DrawOnTop extends View {
Bitmap mBitmap;
Paint mPaintBlack;
Paint mPaintYellow;
Paint mPaintRed;
Paint mPaintGreen;
Paint mPaintBlue;
Paint mPaintGray;

byte[] mYUVData;
int[] mRGBData;
int mImageWidth, mImageHeight;
int[] mRedHistogram;
int[] mGreenHistogram;
int[] mBlueHistogram;
double[] mBinSquared;

private DrawOnTop(Context context) {
super(context);

mPaintBlack = new Paint();
mPaintBlack.setStyle(Paint.Style.FILL);
mPaintBlack.setColor(Color.BLACK);
mPaintBlack.setTextSize(25);

mPaintYellow = new Paint();
mPaintYellow.setStyle(Paint.Style.FILL);
mPaintYellow.setColor(Color.YELLOW);
mPaintYellow.setTextSize(25);

mPaintRed = new Paint();
mPaintRed.setStyle(Paint.Style.FILL);
mPaintRed.setColor(Color.RED);
mPaintRed.setTextSize(25);

mPaintGreen = new Paint();
mPaintGreen.setStyle(Paint.Style.FILL);
mPaintGreen.setColor(Color.GREEN);
mPaintGreen.setTextSize(25);

mPaintBlue = new Paint();
mPaintBlue.setStyle(Paint.Style.FILL);
mPaintBlue.setColor(Color.BLUE);
mPaintBlue.setTextSize(25);

mPaintGray = new Paint();
mPaintGray.setStyle(Paint.Style.FILL);
mPaintGray.setColor(Color.GRAY);
mPaintGray.setTextSize(25);


mBitmap = null;
mYUVData = null;
mRGBData = null;
mRedHistogram = new int[256];
mGreenHistogram = new int[256];
mBlueHistogram = new int[256];
mBinSquared = new double[256];
for (int bin = 0; bin < 256; bin++)
{
mBinSquared[bin] = ((double)bin) * bin;
} // bin
}
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null)
{
canvas.drawColor(Color.WHITE);

int canvasWidth = 255;
int canvasHeight =255;
int newImageWidth = canvasWidth;
int newImageHeight = canvasHeight;
int marginWidth = (canvasWidth - newImageWidth)/2;

// Convert from YUV to RGB
decodeYUV420SP(mRGBData, mYUVData, mImageWidth, mImageHeight);

// Draw bitmap
mBitmap.setPixels(mRGBData, 0, mImageWidth, 0, 0,
mImageWidth, mImageHeight);

// Draw black borders
canvas.drawRect(0, 0, marginWidth, canvasHeight, mPaintBlack);
canvas.drawRect(canvasWidth - marginWidth, 0,
canvasWidth, canvasHeight, mPaintBlack);

// Calculate histogram
calculateIntensityHistogram(mRGBData, mRedHistogram,
mImageWidth, mImageHeight, 0);
calculateIntensityHistogram(mRGBData, mGreenHistogram,
mImageWidth, mImageHeight, 1);
calculateIntensityHistogram(mRGBData, mBlueHistogram,
mImageWidth, mImageHeight, 2);

// Calculate mean
double imageRedMean = 0, imageGreenMean = 0, imageBlueMean = 0;
double redHistogramSum = 0, greenHistogramSum = 0, blueHistogramSum = 0;

for (int bin = 0; bin < 256; bin++)
{
imageRedMean += mRedHistogram[bin] * bin;
redHistogramSum += mRedHistogram[bin];
imageGreenMean += mGreenHistogram[bin] * bin;
greenHistogramSum += mGreenHistogram[bin];
imageBlueMean += mBlueHistogram[bin] * bin;
blueHistogramSum += mBlueHistogram[bin];
} // bin
imageRedMean /= redHistogramSum;
imageGreenMean /= greenHistogramSum;
imageBlueMean /= blueHistogramSum;

// Draw red intensity histogram
float barMaxHeight = 5000;
float barWidth = ((float)newImageWidth) / 256;
float barMarginHeight = 2;
RectF barRect = new RectF();
barRect.bottom = canvasHeight -50 ;
barRect.left = marginWidth;
barRect.right = barRect.left + barWidth;
for (int bin = 0; bin < 255; bin++)
{
float prob = (float)mRedHistogram[bin] / (float)redHistogramSum;
barRect.top = barRect.bottom -
Math.min(100,prob*barMaxHeight) - barMarginHeight;
canvas.drawRect(barRect, mPaintBlack);
barRect.top += barMarginHeight;
canvas.drawRect(barRect, mPaintGray);
barRect.left += barWidth;
barRect.right += barWidth;
} // bin

// Draw green intensity histogram
barRect.bottom = canvasHeight -50 ;
barRect.left = marginWidth;
barRect.right = barRect.left + barWidth;
for (int bin = 0; bin < 255; bin++)
{
barRect.top = barRect.bottom - Math.min(100, ((float)mGreenHistogram[bin])/((float)greenHistogramSum) * barMaxHeight) - barMarginHeight;
canvas.drawRect(barRect, mPaintBlack);
barRect.top += barMarginHeight;
canvas.drawRect(barRect, mPaintGray);
barRect.left += barWidth;
barRect.right += barWidth;
} // bin

// Draw blue intensity histogram
barRect.bottom = canvasHeight -50 ;
barRect.left = marginWidth;
barRect.right = barRect.left + barWidth;
for (int bin = 0; bin < 255; bin++)
{
barRect.top = barRect.bottom - Math.min(100, ((float)mBlueHistogram[bin])/((float)blueHistogramSum) * barMaxHeight) - barMarginHeight;
canvas.drawRect(barRect, mPaintBlack);
barRect.top += barMarginHeight;
canvas.drawRect(barRect, mPaintGray);
barRect.left += barWidth;
barRect.right += barWidth;
} // bin
} // end if statement

super.onDraw(canvas);

}

private void decodeYUV420SP(int[] rgb, byte[] yuv420sp, int width, int height) {
final int frameSize = width * height;

for (int j = 0, yp = 0; j < height; j++) {
int uvp = frameSize + (j >> 1) * width, u = 0, v = 0;
for (int i = 0; i < width; i++, yp++) {
int y = (0xff & ((int) yuv420sp[yp])) - 16;
if (y < 0) y = 0;
if ((i & 1) == 0) {
v = (0xff & yuv420sp[uvp++]) - 128;
u = (0xff & yuv420sp[uvp++]) - 128;
}

int y1192 = 1192 * y;
int r = (y1192 + 1634 * v);
int g = (y1192 - 833 * v - 400 * u);
int b = (y1192 + 2066 * u);

if (r < 0) r = 0; else if (r > 262143) r = 262143;
if (g < 0) g = 0; else if (g > 262143) g = 262143;
if (b < 0) b = 0; else if (b > 262143) b = 262143;

rgb[yp] = 0xff000000 | ((r << 6) & 0xff0000) | ((g >> 2) & 0xff00) | ((b >> 10) & 0xff);
}
}
}


private void calculateIntensityHistogram(int[] rgb, int[] histogram, int width, int height, int component)
{
for (int bin = 0; bin < 256; bin++)
{
histogram[bin] = 0;
} // bin
if (component == 0) // red
{
for (int pix = 0; pix < width*height; pix += 3)
{
int pixVal = (rgb[pix] >> 16) & 0xff;
histogram[ pixVal ]++;
} // pix
}
else if (component == 1) // green
{
for (int pix = 0; pix < width*height; pix += 3)
{
int pixVal = (rgb[pix] >> 8) & 0xff;
histogram[ pixVal ]++;
} // pix
}
else // blue
{
for (int pix = 0; pix < width*height; pix += 3)
{
int pixVal = rgb[pix] & 0xff;
histogram[ pixVal ]++;
} // pix
}
}
}
}



但它没有生成可靠的直方图,我需要生成与 Adob​​e Photoshop 中相同的直方图。
ios 中,它使用以下代码生成与 Adob​​e Photoshop 中相同的直方图。

 -(void)readImage:(UIImage*)image
{
CGImageRef imageRef = [image CGImage];
NSUInteger width = CGImageGetWidth(imageRef);
NSUInteger height = CGImageGetHeight(imageRef);
// NSLog(@"histogram width:- %d",width);
// NSLog(@"histogram height:- %d",height);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
unsigned char *rawData = (unsigned char*) calloc(height * width * 4, sizeof(unsigned char));
NSUInteger bytesPerPixel = 4;
NSUInteger bytesPerRow = bytesPerPixel * width;
NSUInteger bitsPerComponent = 8;
CGContextRef context = CGBitmapContextCreate(rawData, width, height, bitsPerComponent, bytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast | kCGBitmapByteOrder32Big);
CGColorSpaceRelease(colorSpace);
CGContextDrawImage(context, CGRectMake(0, 0, width, height), imageRef);
CGContextRelease(context);

for (int yy=0;yy<height; yy++)
{
for (int xx=0; xx<width; xx++)
{
// Now your rawData contains the image data in the RGBA8888 pixel format.
int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
for (int ii = 0 ; ii < 1 ; ++ii)
{
CGFloat red = (rawData[byteIndex] * 1.0) ;
CGFloat green = (rawData[byteIndex + 1] * 1.0) ;
CGFloat blue = (rawData[byteIndex + 2] * 1.0) ;
// CGFloat alpha = (rawData[byteIndex + 3] * 1.0) / 255.0;
byteIndex += 4;

// TYPE CASTING ABOVE FLOAT VALUES TO THAT THEY CAN BE MATCHED WITH ARRAY'S INDEX.

int redValue = (int)red;
int greenValue = (int)green;
int blueValue = (int)blue;


// THESE COUNTERS COUNT " TOTAL NUMBER OF PIXELS " FOR THAT Red , Green or Blue Value IN ENTIRE IMAGE.

fltR[redValue]++;
fltG[greenValue]++;
fltB[blueValue]++;
}
}
}
[self makeArrays];


// for (int yy=0;yy<height; yy++)
// {
// for (int xx=0; xx<width; xx++)
// {
// int byteIndex = (bytesPerRow * yy) + xx * bytesPerPixel;
// rawData [byteIndex] = nil;
// }
// }
// rawData = 0;
// rawData = nil;
static unsigned updateCounter = 0;
memset(rawData, updateCounter & 0xff, width*height*4);
free(rawData);
rawData = NULL;

for(int i=0;i<=255;i++){
fltR[i]=0;
fltG[i]=0;
fltB[i]=0;
}
colorSpace = nil;
}

-(void)makeArrays
{
float max=0;
int maxR=0;
int maxG=0;
int maxB=0;



// PERFORMING SUMMESION OF ALL RED , GREEN AND BLUE VLAUES GRADUALLY TO TAKE AVERAGE OF THEM
// NSLog(@"makeArray :- ,fltR[i] = %f ,fltG[i] = %f ,fltB[i] = %f",fltR[i],fltG[i],fltB[i])
for (int i=0; i<=255; i++)
{
// NSLog(@"makeArray :- ,fltR[i] = %f ,fltG[i] = %f ,fltB[i] = %f",fltR[i],fltG[i],fltB[i]);
maxR += fltR[i];
maxG += fltG[i];
maxB += fltB[i];
}


// CALCULATING AVERAGE OF ALL red, green and blue values.
maxR = maxR/255;
maxG = maxG/255;
maxB = maxB/255;


// As I AM GENERATING 3 GRAPHS , ITS COMPULSARY TO KEEP THEM ON SCREEN SO TAKING THEIR AVERAGE.
max = (maxR+maxG+maxB)/3;

// DEVIDED BY 8 TO GET GRAPH OF THE SAME SIZE AS ITS IN PREVIEW
max = max*2.5;
arrAllPoints = [[NSMutableArray alloc] init];
for (int i=0; i<=255; i++)
{
ClsDrawPoint *objPoint = [[ClsDrawPoint alloc] init];
objPoint.x = i;
objPoint.y = fltR[i]*scale/max;
[arrAllPoints addObject:objPoint];
}

redGraphView.arrRedPoints = arrAllPoints;
// redGraphView.graphColor = [UIColor redColor];
redGraphView.graphColor = [UIColor whiteColor];
[redGraphView drawGraphForArray:arrAllPoints]; /* redGraphView is an object of ClsDraw (custom class of UIView) and this call drws graph from the points of arrAllPoints */

arrAllPoints = [[NSMutableArray alloc] init];

for (int i=0; i<=255; i++)
{
ClsDrawPoint *objPoint = [[ClsDrawPoint alloc] init];
objPoint.x = i;
objPoint.y = fltG[i]*scale/max;
[arrAllPoints addObject:objPoint];
}

greenGraphView.arrRedPoints = arrAllPoints;
// greenGraphView.graphColor = [UIColor greenColor];
greenGraphView.graphColor = [UIColor whiteColor];
[greenGraphView drawGraphForArray:arrAllPoints]; /* greenGraphView is an object of ClsDraw (custom class of UIView) and this call drws graph from the points of arrAllPoints */

arrAllPoints = [[NSMutableArray alloc] init];

for (int i=0; i<=255; i++)
{
ClsDrawPoint *objPoint = [[ClsDrawPoint alloc] init];
objPoint.x = i;
objPoint.y = fltB[i]*scale/max;
[arrAllPoints addObject:objPoint];
}
blueGraphView.arrRedPoints = arrAllPoints;
// blueGraphView.graphColor = [UIColor blueColor];
blueGraphView.graphColor = [UIColor whiteColor];
[blueGraphView drawGraphForArray:arrAllPoints]; /* blueGraphView is an object of ClsDraw (custom class of UIView) and this call drws graph from the points of arrAllPoints */


// THE COORDINATE SYSTEM OF IOS IS TOTALLY OPPOSITE TO THAT OF THE MAC'S SO ROTATED IT WITH REFERENCE TO X - axis.
blueGraphView.layer.transform = CATransform3DMakeRotation(M_PI, 1.0,0.0, 0.0);
redGraphView.layer.transform = CATransform3DMakeRotation(M_PI, 1.0,0.0, 0.0);
greenGraphView.layer.transform = CATransform3DMakeRotation(M_PI, 1.0,0.0, 0.0);
}

我试图为它找到 Adob​​e Photoshop android api,但没有找到。有没有其他的api可以开发直方图应用?



谢谢,

最佳答案

最后我得到了解决方案&我用下面的代码创建了彩色直方图,

编辑:
我已经把我的完整代码,

DangiAndroidHistogram.java

import java.io.IOException;
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;

import com.example.myandroidhistogram.R;

public class DangiAndroidHistogram 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_main);

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);
}

}

}
}

@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;

}
}



activity_main.xml

<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="horizontal"
android:background="@android:color/black">

<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="257dp"
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="257dp"
android:layout_height="140dp"
android:orientation="vertical" >
</LinearLayout>
</LinearLayout>

<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

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

<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"/>

</RelativeLayout>

</LinearLayout>



我希望这个例子也能帮助其他人..!

关于android - 如何在 Android 中生成图像直方图?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17740059/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com