我尝试从opencv跟进该教程,不同之处在于我使用的是Android。这是link。
在尝试获取新Mat的新值时,出现了错误。
newImageData[(y * mRgba.cols() + x) * mRgba.channels() + c] = saturate(alpha * pixelValue + beta);
这就是我使用的所有代码方法。
public Bitmap brightAndContrast(Bitmap bitmap){
double alpha = 2.0;
int beta = 50;
Mat mRgba = new Mat();
Mat mResult = Mat.zeros(mRgba.size(), mRgba.type());
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap resultBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Utils.bitmapToMat(bitmap, mRgba);
byte[] imageData = new byte[(int) (mRgba.total()*mRgba.channels())];
mRgba.get(0, 0, imageData);
byte[] newImageData = new byte[(int) (mResult.total()*mResult.channels())];
for (int y = 0; y < mRgba.rows(); y++) {
for (int x = 0; x < mRgba.cols(); x++) {
for (int c = 0; c < mRgba.channels(); c++) {
double pixelValue = imageData[(y * mRgba.cols() + x) * mRgba.channels() + c];
pixelValue = pixelValue < 0 ? pixelValue + 256 : pixelValue;
newImageData[(y * mRgba.cols() + x) * mRgba.channels() + c] = saturate(alpha * pixelValue + beta); // this is where the line 101
}
}
}
mResult.put(0, 0, newImageData);
Utils.matToBitmap(mResult, resultBitmap);
return resultBitmap;
}
private byte saturate(double val) {
int iVal = (int) Math.round(val);
iVal = iVal > 255 ? 255 : (iVal < 0 ? 0 : iVal);
return (byte) iVal;
}
那么为什么它越界呢? 这是我得到的错误
java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at com.wannatry.tryapps.OpenCVConverter.brightAndContrast(OpenCVConverter.java:101)
at com.wannatry.tryapps.MainActivity$15.onClick(MainActivity.java:232)
at android.view.View.performClick(View.java:5740)
at android.view.View$PerformClick.run(View.java:22947)
已编辑 这是教程中的C ++代码
new_image.at<Vec3b>(y,x)[c] = saturate_cast<uchar>( alpha*image.at<Vec3b>(y,x)[c] + beta );
并翻译为此代码
double pixelValue = imageData[(y * image.cols() + x) * image.channels() + c]; pixelValue = pixelValue < 0 ? pixelValue + 256 : pixelValue; newImageData[(y * image.cols() + x) * image.channels() + c] = saturate(alpha * pixelValue + beta);