Comments (8)
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.
Can you please provide a few more details? Sample code that triggers your issue?
from camera-samples.
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.
A few follow-up questions:
- What specific line is throwing the error?
- Can you paste the stack trace as well?
- Does this happen when you run the sample as-is?
- If you modified the sample, can you tell us what you changed that causes the error?
from camera-samples.
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.
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.
Closing after 30+ days of inactivity. Feel free to reopen if you are still encountering this issue.
from camera-samples.
This issue not resolved yet, i am also facing the same issue
from camera-samples.
Related Issues (20)
- CameraXBasic example version update? current is: v1.2.2, and sample still in v1.1.0-beta01
- Try android app
- Demo request, wide angel and ultra wide angle
- Switching camera
- I want to switch cameras from another activity
- Is it really not possible to get CPU access to Image data and Video Recording in the same pipeline? HOT 1
- Where are the "Dual concurrent camera" CameraX Examples? HOT 5
- How to use camerax 1.3.0-alpha04 to open two cameras HOT 7
- Image Analysis results are not the same as Preview
- Camera 2 Pixel Device E/CameraDevice-JV-0( 3086): Receive capture error on unknown request ID 14
- Cannot build Camera2Basic HOT 1
- Camera2.Basic crashes when press button HOT 1
- Text overlay on top of Texture view and render to save it along with video. Camera2 or X api HOT 10
- camera2video hdr hlg->pq
- Concurrent camera error
- OverlayEffect sample code HOT 2
- Update CameraX example? HOT 1
- Incorrect colors - greenish image HOT 1
- Yuv To Rgb Converter
- Camera2Extensions build issue
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
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.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from camera-samples.