Java -将新绘制的画布保存为位图并在imageView中显示



我有这个代码,我正在接收基于检测对象的RectF坐标,从用户上传了一个图像。

img = Bitmap.createScaledBitmap(img, 128, 128, true);
try {
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
// Releases model resources if no longer used.
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type and its accuracy score
objecttv.setText(category);
scoretv.setText(Float.toString(score));
textBox.setText(newText);

boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Paint.Style.STROKE);
// here I am trying to create a new canvas to draw on with the location provided by the model and then save that back to a bitmap to display back with the newly drawn rectangle.
Canvas canvas = new Canvas(img);
canvas.drawRect(location,boxPaint);

imageBox.setImageBitmap(img);
}

这显然是错误的,因为我收到的是java.lang.NullPointerException: Attempt to invoke virtual method 'void android.graphics.Paint.setColor(int)' on a null object reference

我怎样才能修改它,在原始图像上绘制新创建的矩形并将其显示回我的imageView?

我是这样做的:

try {
Android model = Android.newInstance(getApplicationContext());
// Creates inputs for reference.
TensorImage image = TensorImage.fromBitmap(img);
// Runs model inference and gets result.
Android.Outputs outputs = model.process(image);
Android.DetectionResult detectionResult = outputs.getDetectionResultList().get(0);
// Gets result from DetectionResult.
float score = detectionResult.getScoreAsFloat();
RectF location = detectionResult.getLocationAsRectF();
String category = detectionResult.getCategoryAsString();
//Create a new canvas to draw on
Canvas canvas = new Canvas(img);
//draw on the canvas with the given location from the model
drawBoundingBox(canvas, location);
// Releases model resources if no longer used.
model.close();
// here we will print out the results of the object to text views based on the image that is inputted by the user
// we print out object type, accuracy score and location of object on the image
objecttv.setText(category);
scoretv.setText(Float.toString(score));
textBox.setText(newText);
imageBox.setImageBitmap(img);
}
void drawBoundingBox(Canvas canvas, RectF location) {
// Draw what you want
Paint boxPaint = new Paint();
boxPaint.setColor(Color.RED);
boxPaint.setAlpha(200);
boxPaint.setStyle(Paint.Style.STROKE);
canvas.drawRect(location, boxPaint);
}

最新更新