android 黑白,使用Android拍摄黑白照片(黑白)

小编典典

如果您希望图像为1位黑白,则可以使用简单的(慢速)阈值算法

public static Bitmap createBlackAndWhite(Bitmap src) {

int width = src.getWidth();

int height = src.getHeight();

// create output bitmap

Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

// color information

int A, R, G, B;

int pixel;

// scan through all pixels

for (int x = 0; x < width; ++x) {

for (int y = 0; y < height; ++y) {

// get pixel color

pixel = src.getPixel(x, y);

A = Color.alpha(pixel);

R = Color.red(pixel);

G = Color.green(pixel);

B = Color.blue(pixel);

int gray = (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);

// use 128 as threshold, above -> white, below -> black

if (gray > 128)

gray = 255;

else

gray = 0;

// set new pixel color to output bitmap

bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray));

}

}

return bmOut;

}

但是,根据看起来不太好的东西,要获得更好的结果,您需要使用抖动算法,请参阅算法概述

-这是阈值方法。

对于256级灰度转换:

根据http://www.mathworks.de/help/toolbox/images/ref/rgb2gray.html,您可以计算每个像素的灰度值,以gray

= 0.2989 * R + 0.5870 * G + 0.1140 * B将其转换为

public static Bitmap createGrayscale(Bitmap src) {

int width = src.getWidth();

int height = src.getHeight();

// create output bitmap

Bitmap bmOut = Bitmap.createBitmap(width, height, src.getConfig());

// color information

int A, R, G, B;

int pixel;

// scan through all pixels

for (int x = 0; x < width; ++x) {

for (int y = 0; y < height; ++y) {

// get pixel color

pixel = src.getPixel(x, y);

A = Color.alpha(pixel);

R = Color.red(pixel);

G = Color.green(pixel);

B = Color.blue(pixel);

int gray = (int) (0.2989 * R + 0.5870 * G + 0.1140 * B);

// set new pixel color to output bitmap

bmOut.setPixel(x, y, Color.argb(A, gray, gray, gray));

}

}

return bmOut;

}

但这很慢,因为您必须分别为数百万个像素执行此操作。

具有更好的方法来实现这一点。

// code from that answer put into method from above

public static Bitmap createGrayscale(Bitmap src) {

int width = src.getWidth();

int height = src.getHeight();

Bitmap bmOut = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

Canvas canvas = new Canvas(bmOut);

ColorMatrix ma = new ColorMatrix();

ma.setSaturation(0);

Paint paint = new Paint();

paint.setColorFilter(new ColorMatrixColorFilter(ma));

canvas.drawBitmap(src, 0, 0, paint);

return bmOut;

}

2020-10-25

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值