Мое приложение зависает или становится черным при использовании аппаратно-интенсивного алгоритма - PullRequest
0 голосов
/ 24 мая 2018

Итак, я разрабатываю приложение для Android для школьного проекта, оно позволяет пользователю либо сделать снимок, либо загрузить изображение из галереи, а затем запускает алгоритм кластеризации k-средних для изображения, чтобы вывести наиболее доминирующие цвета.(https://buzzrobot.com/dominant-colors-in-an-image-using-k-means-clustering-3c7af4622036) Однако, когда изображение выбрано, приложение для Android либо становится черным, либо зависает. Я не знаю, что это за ошибка или как ее исправить, и в отладчике ошибки нет, и я не знаю достаточно о платформе Android, чтобы иметь интуицию для такой проблемы. Любая помощь будет высоко ценится!

это кнопка функции:

public void loadFromGallery(View view) {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, RESULT_LOAD_IMG);
}
public void takePhoto(View view){
    Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null){
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

, и этофункция вызывается при возврате фотографии: и строка, которая вызывает K-Means:

ArrayList<Point> colors = c.getColors(selectedImage, 4, 10);

, и, как вы, вероятно, видите, без этой строки приложение работает отлично, но с ним не работает. Коддля этой функции работает, и иногда приложение будет работать нормально и выводить цвета, но редко. Поэтому я думаю, что это как-то связано слимит ресурсов или срок?

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data){
    super.onActivityResult(requestCode, resultCode, data);

    if (resultCode == RESULT_OK){
        try {
            final Uri imageUri = data.getData();
            final InputStream imageStream = getContentResolver().openInputStream(imageUri);
            //get and shrink bitmap
            final Bitmap selectedImage = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(imageStream), 100, 100, true);

            //run kmeans
            ColorFinder c = new ColorFinder();
            ArrayList<Point> colors = c.getColors(selectedImage, 4, 10);
            //colors of points in android color format


            ArrayList<Integer> cs = new ArrayList<Integer>(4);
            for (Point color : colors){
                cs.add(hexToColor(color));
            }
            image.setImageBitmap(selectedImage);

            ColorDrawable drawable1 =  (ColorDrawable) color1.getDrawable();
            drawable1.setColor(cs.get(0));
            textView1.setText(c.RGBtoHex(colors.get(0)));
            ColorDrawable drawable2 = (ColorDrawable)color2.getDrawable();
            drawable2.setColor(cs.get(1));
            textView2.setText(c.RGBtoHex(colors.get(1)));
            ColorDrawable drawable3 = (ColorDrawable)color3.getDrawable();
            drawable3.setColor(cs.get(2));
            textView3.setText(c.RGBtoHex(colors.get(2)));
            ColorDrawable drawable4 = (ColorDrawable)color4.getDrawable();
            drawable4.setColor(cs.get(3));
            textView4.setText(c.RGBtoHex(colors.get(3)));


        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(MainScreen.this, "Something went wrong", Toast.LENGTH_LONG).show();

        }
    } else {
        Toast.makeText(MainScreen.this, "You havent picked image", Toast.LENGTH_LONG).show();
    }
}

1 Ответ

0 голосов
/ 24 мая 2018

Вы выполняете операцию ввода-вывода в главном потоке, используйте асинхронную задачу в результатах активности, чтобы избавиться от черного экрана

private class AsyncTaskRunner extends AsyncTask<String, String, String> {

    private String resp;
    ProgressDialog progressDialog;

    @Override
    protected String doInBackground(String... params) {
        try {
            final Uri imageUri = data.getData();
            final InputStream imageStream = getContentResolver().openInputStream(imageUri);
            //get and shrink bitmap
            final Bitmap selectedImage = Bitmap.createScaledBitmap(BitmapFactory.decodeStream(imageStream), 100, 100, true);

            //run kmeans
            ColorFinder c = new ColorFinder();
            ArrayList<Point> colors = c.getColors(selectedImage, 4, 10);
            //colors of points in android color format


            ArrayList<Integer> cs = new ArrayList<Integer>(4);
            for (Point color : colors){
                cs.add(hexToColor(color));
            }
            image.setImageBitmap(selectedImage);




        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(MainScreen.this, "Something went wrong", Toast.LENGTH_LONG).show();

        }
    }


    @Override
    protected void onPostExecute(String result) {
        // execution of result of Long time consuming operation
        progressDialog.dismiss();
        ColorDrawable drawable1 =  (ColorDrawable) color1.getDrawable();
            drawable1.setColor(cs.get(0));
            textView1.setText(c.RGBtoHex(colors.get(0)));
            ColorDrawable drawable2 = (ColorDrawable)color2.getDrawable();
            drawable2.setColor(cs.get(1));
            textView2.setText(c.RGBtoHex(colors.get(1)));
            ColorDrawable drawable3 = (ColorDrawable)color3.getDrawable();
            drawable3.setColor(cs.get(2));
            textView3.setText(c.RGBtoHex(colors.get(2)));
            ColorDrawable drawable4 = (ColorDrawable)color4.getDrawable();
            drawable4.setColor(cs.get(3));
            textView4.setText(c.RGBtoHex(colors.get(3)));
    }


    @Override
    protected void onPreExecute() {
        progressDialog = ProgressDialog.show(MainActivity.this,
                "ProgressDialog",
                "Loading");
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...