Git Product home page Git Product logo

Comments (8)

P1514 avatar P1514 commented on July 4, 2024 2

Hello just in case someone like me is having this issue, I'm using a Nokia 6.1 only managed to have this code to work with the following camera2 version 'androidx.camera:camera-camera2:1.0.0-alpha03'
firebase-ml didn't seem to impact here. The error mentioned still occurs but the camera at least works

from camera-samples.

owahltinez avatar owahltinez commented on July 4, 2024

Can you please provide a few more details? Sample code that triggers your issue?

from camera-samples.

ajayVinay avatar ajayVinay commented on July 4, 2024

I did this .....

/////#######################////
package com.example.cameraxapp

import android.Manifest
import android.content.pm.PackageManager
import android.graphics.Matrix
import android.os.Bundle
import android.os.Handler
import android.os.HandlerThread
import android.util.Log
import android.util.Rational
import android.util.Size
import android.view.Surface
import android.view.TextureView
import android.view.ViewGroup
import android.widget.ImageButton
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.camera.core.*
import androidx.core.content.ContextCompat
import androidx.lifecycle.LifecycleOwner
import java.io.File
import java.nio.ByteBuffer
import java.util.concurrent.TimeUnit

// This is an arbitrary number we are using to keep tab of the permission
// request. Where an app has multiple context for requesting permission,
// this can help differentiate the different contexts
private const val REQUEST_CODE_PERMISSIONS = 10

// This is an array of all the permission specified in the manifest
private val REQUIRED_PERMISSIONS = arrayOf(Manifest.permission.CAMERA)

class MainActivity : AppCompatActivity(),LifecycleOwner {

private lateinit var viewFinder: TextureView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

}
// this  method create for implement cameraX operations
// create configuration object for the viewfinder use case
private fun startCamera() {

    val previewConfig = PreviewConfig.Builder().apply {

        setTargetAspectRatio(Rational(1, 1))
        setTargetResolution(Size(640, 640))

    }.build()

    // Build the viewFinder use case
    val preview = Preview(previewConfig)

    preview.setOnPreviewOutputUpdateListener {

        // To update the surfaceTexture, we have to remove it and re-add it
        val parent = viewFinder.parent as ViewGroup
        parent.removeView(viewFinder)
        parent.addView(viewFinder, 0)

        // it :- this is return current value
        viewFinder.surfaceTexture = it.surfaceTexture
        updateTransform()
    }

    // Create configuration object for the image capture use case
    val imageCaptureConfig = ImageCaptureConfig.Builder()
        .apply {
            setTargetAspectRatio(Rational(1, 1))
            // We don't set a resolution for image capture; instead, we
            // select a capture mode which will infer the appropriate
            // resolution based on aspect ration and requested mode
            setCaptureMode(ImageCapture.CaptureMode.MIN_LATENCY)
        }.build()

    // Build the image capture use case and attach button click listener
    val imageCapture = ImageCapture(imageCaptureConfig)
    findViewById<ImageButton>(R.id.capture_button).setOnClickListener {
        val file = File(externalMediaDirs.first(),
            "${System.currentTimeMillis()}.jpg")
        imageCapture.takePicture(file,
            object : ImageCapture.OnImageSavedListener {
                override fun onError(error: ImageCapture.UseCaseError,
                                     message: String, exc: Throwable?) {
                    val msg = "Photo capture failed: $message"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.e("CameraXApp", msg)
                    exc?.printStackTrace()
                }

                override fun onImageSaved(file: File) {
                    val msg = "Photo capture succeeded: ${file.absolutePath}"
                    Toast.makeText(baseContext, msg, Toast.LENGTH_SHORT).show()
                    Log.d("CameraXApp", msg)
                }
            })
    }

    // Setup image analysis pipeline that computes average pixel luminance
    val analyzerConfig = ImageAnalysisConfig.Builder().apply {
        // Use a worker thread for image analysis to prevent glitches
        val analyzerThread = HandlerThread(
            "LuminosityAnalysis").apply { start() }
        setCallbackHandler(Handler(analyzerThread.looper))
        // In our analysis, we care more about the latest image than
        // analyzing *every* image
        setImageReaderMode(
            ImageAnalysis.ImageReaderMode.ACQUIRE_LATEST_IMAGE)
    }.build()

    // Build the image analysis use case and instantiate our analyzer
    val analyzerUseCase = ImageAnalysis(analyzerConfig).apply {
        analyzer = LuminosityAnalyzer()
    }

    // bind use cases to lifeCycle
    // If Android Studio complains about "this" being not a LifecycleOwner
    // try rebuilding the project or updating the appcompat dependency to
    // version 1.1.0 or higher.
    CameraX.bindToLifecycle(this, preview,imageCapture)

}

// this method is used for implement camera viewFinder transformation
private fun updateTransform() {

    val matrix = Matrix()

    //compute the center of the view finder
    val centerX = viewFinder.width/2f
    val centerY = viewFinder.height/2f


    //correct preview output to account for display rotation
    val rotationDegrees = when(viewFinder.display.rotation){

        Surface.ROTATION_0 ->0
        Surface.ROTATION_90 ->90
        Surface.ROTATION_180 ->180
        Surface.ROTATION_270 ->270
        else ->return
    }
    matrix.postRotate(-rotationDegrees.toFloat(), centerX, centerY)

    // Finally, apply transformations to our TextureView
    viewFinder.setTransform(matrix)

}

    /**
     * Process result from permission request dialog box, has the request
     * been granted? If yes, start Camera. Otherwise display a toast
     */
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {

        if (requestCode == REQUEST_CODE_PERMISSIONS) {
            if (allPermissionsGranted()) {
                viewFinder.post { startCamera() }

            } else {
                Toast.makeText(this, "Permission not granted by the usser", Toast.LENGTH_LONG).show()
                finish()
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    /**
     * Check if all permission specified in the manifest have been granted
     */
  private  fun allPermissionsGranted(): Boolean {

        for (permission in REQUIRED_PERMISSIONS) {
            if (ContextCompat.checkSelfPermission(
                    this, permission) != PackageManager.PERMISSION_GRANTED
            ) {
                return false
            }
        }
        return true
    }

}

private class LuminosityAnalyzer : ImageAnalysis.Analyzer {
private var lastAnalyzedTimestamp = 0L

/**
 * Helper extension function used to extract a byte array from an
 * image plane buffer
 */
private fun ByteBuffer.toByteArray(): ByteArray {
    rewind()    // Rewind the buffer to zero
    val data = ByteArray(remaining())
    get(data)   // Copy the buffer into a byte array
    return data // Return the byte array
}

override fun analyze(image: ImageProxy, rotationDegrees: Int) {
    val currentTimestamp = System.currentTimeMillis()
    // Calculate the average luma no more often than every second
    if (currentTimestamp - lastAnalyzedTimestamp >=
        TimeUnit.SECONDS.toMillis(1)) {
        // Since format in ImageAnalysis is YUV, image.planes[0]
        // contains the Y (luminance) plane
        val buffer = image.planes[0].buffer
        // Extract image data from callback object
        val data = buffer.toByteArray()
        // Convert the data into an array of pixel values
        val pixels = data.map { it.toInt() and 0xFF }
        // Compute average luminance for the image
        val luma = pixels.average()
        // Log the new luma value
        Log.d("CameraXApp", "Average luminosity: $luma")
        // Update timestamp of last analyzed frame
        lastAnalyzedTimestamp = currentTimestamp
    }
}

}

from camera-samples.

owahltinez avatar owahltinez commented on July 4, 2024

A few follow-up questions:

  1. What specific line is throwing the error?
  2. Can you paste the stack trace as well?
  3. Does this happen when you run the sample as-is?
  4. If you modified the sample, can you tell us what you changed that causes the error?

from camera-samples.

ajayVinay avatar ajayVinay commented on July 4, 2024

1.There is no specific line throwing error
3.Yes ,this happen when am i rum sample code
4. No modification sample code

from camera-samples.

owahltinez avatar owahltinez commented on July 4, 2024

Thanks for the feedback. It sounds like the issue may not be with the sample itself, but potentially with the library. Can you please file a bug in the appropriate component of the Android Issue Tracker? It should be https://issuetracker.google.com/components/618491. Please include information about the specific device that you are seeing this on.

from camera-samples.

owahltinez avatar owahltinez commented on July 4, 2024

Closing after 30+ days of inactivity. Feel free to reopen if you are still encountering this issue.

from camera-samples.

RajappaR avatar RajappaR commented on July 4, 2024

This issue not resolved yet, i am also facing the same issue

from camera-samples.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.