You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

能否在Android Studio中使用OpenCV Python?已导入OpenCV

Using OpenCV Python in Android Studio: Feasibility & Step-by-Step Guide

Absolutely! You can use OpenCV Python in Android Studio—Android doesn’t natively support Python, but tools like Chaquopy act as a bridge between Android’s Java/Kotlin environment and Python code. Since you already have OpenCV imported (I assume that’s the Java version?), let’s walk through setting up the Python side properly:

1. Add the Chaquopy Plugin to Your Project

Chaquopy lets you run Python scripts and install Python libraries directly in an Android project. Here’s how to configure it:

  • Open your project-level build.gradle file, and add Chaquopy’s classpath to the buildscript > dependencies block:
    dependencies {
        // Keep your existing dependencies, then add this line
        classpath "com.chaquo.python:gradle:14.0.2" // Use the latest version if available
    }
    
  • Next, open your module-level build.gradle file. Add the Chaquopy plugin to the top plugins block:
    plugins {
        id 'com.android.application'
        id 'com.chaquo.python' // Add this line
    }
    
  • Still in the module-level build.gradle, configure Python and install OpenCV Python under the defaultConfig section:
    android {
        defaultConfig {
            // Your existing config (minSdk, targetSdk, etc.)
            ndk {
                abiFilters "armeabi-v7a", "arm64-v8a", "x86", "x86_64" // Support common device architectures
            }
            python {
                pip {
                    install "opencv-python" // Pulls the Python version of OpenCV
                }
            }
        }
    }
    

2. Write Your OpenCV Python Logic

Create a python folder under src/main (if it doesn’t exist), then make a script like opencv_processing.py:

import cv2
import numpy as np

def convert_to_grayscale(image_path):
    # Load the input image
    img = cv2.imread(image_path)
    # Convert to grayscale using OpenCV
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    # Save the processed image to external storage
    output_path = "/storage/emulated/0/gray_output.jpg"
    cv2.imwrite(output_path, gray_img)
    return output_path

3. Call Python Code from Android (Kotlin Example)

Trigger your OpenCV Python function from an Android Activity using Kotlin:

import com.chaquo.python.Python
import com.chaquo.python.android.AndroidPlatform
import android.util.Log

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

        // Initialize the Python environment if it's not running
        if (!Python.isStarted()) {
            Python.start(AndroidPlatform(this))
        }

        // Access your Python script and execute the function
        val python = Python.getInstance()
        val processingModule = python.getModule("opencv_processing")
        val resultPath = processingModule.callAttr("convert_to_grayscale", "/storage/emulated/0/test_image.jpg").toString()
        
        Log.d("OpenCV-Python", "Processed image saved to: $resultPath")
    }
}

4. Set Up Required Permissions

Add storage permissions to your AndroidManifest.xml to read/write images:

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

For Android 13+, you’ll also need to request these permissions dynamically at runtime (follow standard Android permission practices).

Quick Tips

  • If you previously added the Java version of OpenCV, you can keep it—there’s no conflict with the Python version. Remove the Java dependency if you don’t need it.
  • If pip fails to install OpenCV, try specifying a specific version like install "opencv-python==4.8.0" to avoid compatibility issues.
  • Ensure your emulator/device has enough storage—OpenCV Python takes up a reasonable amount of space.

内容的提问来源于stack exchange,提问作者Vedant Gupta

火山引擎 最新活动