Aus irgendeinem Grund. In dieser Klasse bekomme ich immer eine NullPointerException
. Ich bin wirklich verwirrt und frage mich, ob und von euch kann mir helfenNullPointerException Android Studio
public class MainActivity extends AppCompatActivity {
private static final String TAG = "OCVSample::Activity";
private static Bitmap bmp, yourSelectedImage, bmpimg1, bmpimg2;
private static ImageView iv1, iv2;
private static TextView tv;
private static String path1, path2;
private static String text;
private static Button start;
private static int imgNo = 0;
private static Uri selectedImage;
private static InputStream imageStream;
private static long startTime, endTime;
private static final int SELECT_PHOTO = 100;
private static int descriptor = DescriptorExtractor.BRISK;
private static String descriptorType;
private static int min_dist = 10;
private static int min_matches = 750;
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
private GoogleApiClient client;
public MainActivity() {
Log.i(TAG, "Inititated new " + this.getClass());
}
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS: {
Log.i(TAG, "OpenCV loaded successfully");
}
break;
default: {
super.onManagerConnected(status);
}
break;
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
iv2 = (ImageView) MainActivity.this.findViewById(R.id.img2);
start = (Button) MainActivity.this.findViewById(R.id.button1);
tv = (TextView) MainActivity.this.findViewById(R.id.tv);
run();
}
public void run() {
if (descriptor == DescriptorExtractor.BRISK)
descriptorType = "BRISK";
System.out.println(descriptorType);
tv.setText("Select the two images to be compared.\n" + "DescriptorExtractor:" + descriptorType + "\nHamming distance between descriptors:" + min_dist + "\nMinimum number of good matches:" + min_matches);
iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
iv2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 2;
}
});
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (bmpimg1 != null && bmpimg2 != null) {
bmpimg1 = Bitmap.createScaledBitmap(bmpimg1, 100, 100, true);
bmpimg2 = Bitmap.createScaledBitmap(bmpimg2, 100, 100, true);
Mat img1 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Mat img2 = new Mat();
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_RGBA2GRAY);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_RGBA2GRAY);
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
//Log.d("ImageComparator", "img1:"+img1.rows()+"x"+img1.cols()+" img2:"+img2.rows()+"x"+img2.cols());
Mat hist1 = new Mat();
Mat hist2 = new Mat();
MatOfInt histSize = new MatOfInt(180);
MatOfInt channels = new MatOfInt(0);
ArrayList<Mat> bgr_planes1 = new ArrayList<Mat>();
ArrayList<Mat> bgr_planes2 = new ArrayList<Mat>();
Core.split(img1, bgr_planes1);
Core.split(img2, bgr_planes2);
MatOfFloat histRanges = new MatOfFloat(0f, 180f);
boolean accumulate = false;
Imgproc.calcHist(bgr_planes1, channels, new Mat(), hist1, histSize, histRanges, accumulate);
Core.normalize(hist1, hist1, 0, hist1.rows(), Core.NORM_MINMAX, -1, new Mat());
Imgproc.calcHist(bgr_planes2, channels, new Mat(), hist2, histSize, histRanges, accumulate);
Core.normalize(hist2, hist2, 0, hist2.rows(), Core.NORM_MINMAX, -1, new Mat());
img1.convertTo(img1, CvType.CV_32F);
img2.convertTo(img2, CvType.CV_32F);
hist1.convertTo(hist1, CvType.CV_32F);
hist2.convertTo(hist2, CvType.CV_32F);
double compare = Imgproc.compareHist(hist1, hist2, Imgproc.CV_COMP_CHISQR);
Log.d("ImageComparator", "compare: " + compare);
if (compare > 0 && compare < 1500) {
Toast.makeText(MainActivity.this, "Images may be possible duplicates, verifying", Toast.LENGTH_LONG).show();
new asyncTask(MainActivity.this).execute();
} else if (compare == 0)
Toast.makeText(MainActivity.this, "Images are exact duplicates", Toast.LENGTH_LONG).show();
else
Toast.makeText(MainActivity.this, "Images are not duplicates", Toast.LENGTH_LONG).show();
startTime = System.currentTimeMillis();
} else
Toast.makeText(MainActivity.this,
"You haven't selected images.", Toast.LENGTH_LONG)
.show();
}
});
}
@Override
protected void onNewIntent(Intent newIntent) {
super.onNewIntent(newIntent);
min_dist = newIntent.getExtras().getInt("min_dist");
descriptor = newIntent.getExtras().getInt("descriptor");
min_matches = newIntent.getExtras().getInt("min_matches");
run();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PHOTO:
if (resultCode == RESULT_OK) {
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
if (imgNo == 1) {
iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
bmpimg1 = yourSelectedImage;
} else if (imgNo == 2) {
iv2.setImageBitmap(yourSelectedImage);
path2 = selectedImage.getPath();
bmpimg2 = yourSelectedImage;
}
}
}
}
@Override
public void onPause() {
super.onPause();
}
@Override
public void onResume() {
super.onResume();
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_2_4_4, this, mLoaderCallback);
}
public static class asyncTask extends AsyncTask<Void, Void, Void> {
private static Mat img1, img2, descriptors, dupDescriptors;
private static FeatureDetector detector;
private static DescriptorExtractor DescExtractor;
private static DescriptorMatcher matcher;
private static MatOfKeyPoint keypoints, dupKeypoints;
private static MatOfDMatch matches, matches_final_mat;
private static Bitmap bmp, bmpimg1, bmpimg2;
private static ProgressDialog pd;
private static TextView tv;
private static int descriptor = DescriptorExtractor.BRISK;
private static int min_matches = 750;
private static int min_dist = 10;
private static long endTime;
private static boolean isDuplicate = false;
private MainActivity asyncTaskContext = null;
private static Scalar RED = new Scalar(255, 0, 0);
private static Scalar GREEN = new Scalar(0, 255, 0);
public asyncTask(MainActivity context) {
asyncTaskContext = context;
}
@Override
protected void onPreExecute() {
pd = new ProgressDialog(asyncTaskContext);
pd.setIndeterminate(true);
pd.setCancelable(true);
pd.setCanceledOnTouchOutside(false);
pd.setMessage("Processing...");
pd.show();
}
@Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
compare();
return null;
}
@Override
protected void onPostExecute(Void result) {
try {
Mat img3 = new Mat();
MatOfByte drawnMatches = new MatOfByte();
Features2d.drawMatches(img1, keypoints, img2, dupKeypoints,
matches_final_mat, img3, GREEN, RED, drawnMatches, Features2d.NOT_DRAW_SINGLE_POINTS);
bmp = Bitmap.createBitmap(img3.cols(), img3.rows(),
Bitmap.Config.ARGB_8888);
Imgproc.cvtColor(img3, img3, Imgproc.COLOR_BGR2RGB);
Utils.matToBitmap(img3, bmp);
List<DMatch> finalMatchesList = matches_final_mat.toList();
endTime = System.currentTimeMillis();
if (finalMatchesList.size() > min_matches)// dev discretion for
// number of matches to
// be found for an image
// to be judged as
// duplicates or not
{
tv.setText(finalMatchesList.size()
+ " matches were found. Possible duplicate image.\nTime taken="
+ (endTime - startTime) + "ms");
isDuplicate = true;
} else {
tv.setText(finalMatchesList.size()
+ " matches were found. Images aren't similar.\nTime taken="
+ (endTime - startTime) + "ms");
isDuplicate = false;
}
pd.dismiss();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(asyncTaskContext, e.toString(),
Toast.LENGTH_LONG).show();
}
}
void compare() {
try {
bmpimg1 = bmpimg1.copy(Bitmap.Config.ARGB_8888, true);
bmpimg2 = bmpimg2.copy(Bitmap.Config.ARGB_8888, true);
img1 = new Mat();
img2 = new Mat();
Utils.bitmapToMat(bmpimg1, img1);
Utils.bitmapToMat(bmpimg2, img2);
Imgproc.cvtColor(img1, img1, Imgproc.COLOR_BGR2RGB);
Imgproc.cvtColor(img2, img2, Imgproc.COLOR_BGR2RGB);
detector = FeatureDetector.create(FeatureDetector.PYRAMID_FAST);
DescExtractor = DescriptorExtractor.create(descriptor);
matcher = DescriptorMatcher
.create(DescriptorMatcher.BRUTEFORCE_HAMMING);
keypoints = new MatOfKeyPoint();
dupKeypoints = new MatOfKeyPoint();
descriptors = new Mat();
dupDescriptors = new Mat();
matches = new MatOfDMatch();
detector.detect(img1, keypoints);
Log.d("LOG!", "number of query Keypoints= " + keypoints.size());
detector.detect(img2, dupKeypoints);
Log.d("LOG!", "number of dup Keypoints= " + dupKeypoints.size());
// Descript keypoints
DescExtractor.compute(img1, keypoints, descriptors);
DescExtractor.compute(img2, dupKeypoints, dupDescriptors);
Log.d("LOG!", "number of descriptors= " + descriptors.size());
Log.d("LOG!",
"number of dupDescriptors= " + dupDescriptors.size());
// matching descriptors
matcher.match(descriptors, dupDescriptors, matches);
Log.d("LOG!", "Matches Size " + matches.size());
// New method of finding best matches
List<DMatch> matchesList = matches.toList();
List<DMatch> matches_final = new ArrayList<DMatch>();
for (int i = 0; i < matchesList.size(); i++) {
if (matchesList.get(i).distance <= min_dist) {
matches_final.add(matches.toList().get(i));
}
}
matches_final_mat = new MatOfDMatch();
matches_final_mat.fromList(matches_final);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
auch. Was genau ist ein NullPointerException
und wie verhindere ich es. Entschuldigung, wenn es nicht genug Details gibt, dies ist mein erster Beitrag in diesem Forum. Und was mich verwirrt, ist die logcat:
09-11 19:32:14.998 1506-3141/duketip.comparatortest W/System.err: java.lang.NullPointerException 09-11 19:32:14.998 1506-3141/duketip.comparatortest W/System.err: at duketip.comparatortest.MainActivity$asyncTask.compare(MainActivity.java:337) 09-11 19:32:14.998 1506-3141/duketip.comparatortest W/System.err: at duketip.comparatortest.MainActivity$asyncTask.doInBackground(MainActivity.java:292) 09-11 19:32:15.008 1506-3141/duketip.comparatortest W/System.err: at duketip.comparatortest.MainActivity$asyncTask.doInBackground(MainActivity.java:256) 09-11 19:32:15.008 1506-3141/duketip.comparatortest W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:288) 09-11 19:32:15.008 1506-3141/duketip.comparatortest W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237) 09-11 19:32:15.008 1506-3141/duketip.comparatortest W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 09-11 19:32:15.018 1506-3141/duketip.comparatortest W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 09-11 19:32:15.018 1506-3141/duketip.comparatortest W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 09-11 19:32:15.058 1506-3141/duketip.comparatortest W/System.err: at java.lang.Thread.run(Thread.java:841)
Auf welcher Zeile erhalten Sie die NullPointerException? Überprüfen Sie das Logbuch. – AkashBhave
Lesen Sie den Abschnitt "Wie man fragt" und hören Sie auf, unhöflich zu sein, wenn Sie geholfen werden wollen. – Chisko