في هذا الكود class MainActivity : AppCompatActivity() {

    private lateinit var imageView: ImageView
    private lateinit var selectedImageBitmap: Bitmap
    private lateinit var backgroundBitmap: Bitmap
    private val REQUEST_BACKGROUND_GALLERY = 101
    private val REQUEST_IMAGE_GALLERY = 100
    lateinit var interpreter: Interpreter

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initializeModel()

        imageView = findViewById(R.id.imageView)

        // زر لاختيار الصورة
        val pickImageButton = findViewById<Button>(R.id.pickImageButton)
        pickImageButton.setOnClickListener {
            pickImageFromGallery()
        }

        // زر لاختيار الخلفية الجديدة
        val pickBackgroundButton = findViewById<Button>(R.id.pickBackgroundButton)
        pickBackgroundButton.setOnClickListener {
            pickBackgroundFromGallery()
        }

        // زر لإزالة الخلفية
        val removeBackgroundButton = findViewById<Button>(R.id.removeBackgroundButton)
        removeBackgroundButton.setOnClickListener {
            val removedBackgroundBitmap = removeBackground(selectedImageBitmap)
            imageView.setImageBitmap(removedBackgroundBitmap)
        }

        // زر لتركيب الصورتين
        val mergeImagesButton = findViewById<Button>(R.id.mergeImagesButton)
        mergeImagesButton.setOnClickListener {
            val mergedBitmap = mergeImages(selectedImageBitmap, backgroundBitmap)
            imageView.setImageBitmap(mergedBitmap)
        }
    }

    private fun updateImageView() {
        val newBitmap = mergeImages(selectedImageBitmap, backgroundBitmap)
        imageView.setImageBitmap(newBitmap)

    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_IMAGE_GALLERY && resultCode == RESULT_OK && data != null) {
            val imageUri = data.data
            selectedImageBitmap = MediaStore.Images.Media.getBitmap(this.contentResolver, imageUri)
            updateImageView()
        } else if (requestCode == REQUEST_BACKGROUND_GALLERY && resultCode == RESULT_OK && data != null) {
            val backgroundUri = data.data
            backgroundBitmap =
                MediaStore.Images.Media.getBitmap(this.contentResolver, backgroundUri)
            updateImageView()
        } else {
            Toast.makeText(this, "Error loading image", Toast.LENGTH_SHORT).show()
        }
    }

    private fun mergeImages(imageBitmap: Bitmap, backgroundBitmap: Bitmap): Bitmap {
        val mergedBitmap = Bitmap.createBitmap(
            backgroundBitmap.width,
            backgroundBitmap.height,
            Bitmap.Config.ARGB_8888
        )
        val canvas = Canvas(mergedBitmap)
        canvas.drawBitmap(backgroundBitmap, 0F, 0F, null)
        canvas.drawBitmap(imageBitmap, 0F, 0F, null)
        return mergedBitmap
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_BACKGROUND_GALLERY && grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            pickBackgroundFromGallery()
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun pickBackgroundFromGallery() {
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.READ_MEDIA_IMAGES
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES),
                REQUEST_BACKGROUND_GALLERY
            )
        } else {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            startActivityForResult(intent, REQUEST_BACKGROUND_GALLERY)
        }
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    private fun pickImageFromGallery() {
        if (ContextCompat.checkSelfPermission(
                this,
                android.Manifest.permission.READ_MEDIA_IMAGES
            ) != PackageManager.PERMISSION_GRANTED
        ) {
            ActivityCompat.requestPermissions(
                this,
                arrayOf(android.Manifest.permission.READ_MEDIA_IMAGES),
                REQUEST_IMAGE_GALLERY
            )
        } else {
            val intent = Intent(Intent.ACTION_PICK)
            intent.type = "image/*"
            startActivityForResult(intent, REQUEST_IMAGE_GALLERY)
        }
    }


    private fun initializeModel() {
        val assetManager = assets
        val modelPath = "mobilenetv2_coco_voctrainval.tflite"

        interpreter = Interpreter(loadModelFile(assetManager, modelPath))
    }

    private fun loadModelFile(assetManager: AssetManager, fileName: String): ByteBuffer {
        val fileDescriptor = assetManager.openFd(fileName)
        val inputStream = FileInputStream(fileDescriptor.fileDescriptor)
        val fileChannel = inputStream.channel
        val startOffset = fileDescriptor.startOffset
        val declaredLength = fileDescriptor.declaredLength

        return fileChannel.map(FileChannel.MapMode.READ_ONLY, startOffset, declaredLength)
    }

    private fun removeBackground(image: Bitmap): Bitmap {
        val width = image.width
        val height = image.height

        val inputSize = 513
        val resizeRatio = inputSize / max(width, height).toFloat()
        val resizedWidth = (width * resizeRatio).toInt()
        val resizedHeight = (height * resizeRatio).toInt()

        val resizedImage = Bitmap.createScaledBitmap(image, resizedWidth, resizedHeight, true)
        val convertedImage =
            Bitmap.createBitmap(resizedWidth, resizedHeight, Bitmap.Config.ARGB_8888)

        // عملية إزالة الخلفية
        val inputArray = arrayOf(arrayOf(Array(inputSize) { FloatArray(inputSize) }))
        val outputMap = HashMap<Int, Any>()
        outputMap[0] = Array(resizedHeight) { Array(resizedWidth) { IntArray(1) } }
        interpreter.runForMultipleInputsOutputs(arrayOf(resizedImage), outputMap)

        // لوضع صورة جديدة بالخلفية
        val newBackground = Bitmap.createScaledBitmap(
            BitmapFactory.decodeResource(resources, R.drawable.image1),
            resizedWidth,
            resizedHeight,
            true
        )

        val tempCanvas = Canvas(convertedImage)
        tempCanvas.drawBitmap(newBackground, 0F, 0F, null)
        for (i in 0 until resizedHeight) {
            for (j in 0 until resizedWidth) {
                val pixel = (outputMap[0] as Array<Array<IntArray>>)[i][j][0]
                if (pixel != 0) {
                    convertedImage.setPixel(j, i, resizedImage.getPixel(j, i))
                }
            }
        }

        return convertedImage
    }
} يحدث حطا FATAL EXCEPTION: main
                                                                                                    Process: com.dm.myapplication, PID: 8529
                                                                                                    java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=100, result=-1, data=Intent { dat=content://com.miui.gallery.open/... typ=image/jpeg flg=0x1 }} to activity {com.dm.myapplication/com.dm.myapplication.MainActivity}: kotlin.UninitializedPropertyAccessException: lateinit property backgroundBitmap has not been initialized
                                                                                                    	at android.app.ActivityThread.deliverResults(ActivityThread.java:5538)
                                                                                                    	at android.app.ActivityThread.handleSendResult(ActivityThread.java:5577)
                                                                                                    	at android.app.servertransaction.ActivityResultItem.execute(ActivityResultItem.java:67)
                                                                                                    	at android.app.servertransaction.ActivityTransactionItem.execute(ActivityTransactionItem.java:45)
                                                                                                    	at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
                                                                                                    	at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
                                                                                                    	at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2394)
                                                                                                    	at android.os.Handler.dispatchMessage(Handler.java:106)
                                                                                                    	at android.os.Looper.loopOnce(Looper.java:211)
                                                                                                    	at android.os.Looper.loop(Looper.java:300)
                                                                                                    	at android.app.ActivityThread.main(ActivityThread.java:8296)
                                                                                                    	at java.lang.reflect.Method.invoke(Native Method)
                                                                                                    	at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:559)
                                                                                                    	at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:954)
                                                                                                    Caused by: kotlin.UninitializedPropertyAccessException: lateinit property backgroundBitmap has not been initialized
                                                                                                    	at com.dm.myapplication.MainActivity.updateImageView(MainActivity.kt:75)
                                                                                                    	at com.dm.myapplication.MainActivity.onActivityResult(MainActivity.kt:84)
                                                                                                    	at android.app.Activity.dispatchActivityResult(Activity.java:8908)
                                                                                                    	at android.app.ActivityThread.deliverResults(ActivityThread.java:5531)