Android opencv 识别交通灯的程序
时间: 2023-12-10 14:04:41 浏览: 183
以下是一个简单的 Android OpenCV 交通灯识别程序的示例,假设你已经安装了 OpenCV for Android:
1. 在 Android Studio 中创建一个新的项目,并在 Gradle 文件中添加 OpenCV 依赖项。
2. 将下面的代码复制并粘贴到 MainActivity.java 文件中:
```
import org.opencv.android.BaseLoaderCallback;
import org.opencv.android.CameraBridgeViewBase;
import org.opencv.android.LoaderCallbackInterface;
import org.opencv.android.OpenCVLoader;
import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.core.Point;
import org.opencv.core.Rect;
import org.opencv.core.Scalar;
import org.opencv.core.Size;
import org.opencv.imgproc.Imgproc;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewFrame;
import org.opencv.android.CameraBridgeViewBase.CvCameraViewListener2;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.WindowManager;
public class MainActivity extends Activity implements CvCameraViewListener2 {
private static final String TAG = "MainActivity";
private CameraBridgeViewBase mOpenCvCameraView;
private boolean mIsJavaCamera = true;
private MenuItem mItemSwitchCamera = null;
private Mat mRgba;
private Mat mGray;
private BaseLoaderCallback mLoaderCallback = new BaseLoaderCallback(this) {
@Override
public void onManagerConnected(int status) {
switch (status) {
case LoaderCallbackInterface.SUCCESS:
{
Log.i(TAG, "OpenCV loaded successfully");
mOpenCvCameraView.enableView();
} break;
default:
{
super.onManagerConnected(status);
} break;
}
}
};
public MainActivity() {
Log.i(TAG, "Instantiated new " + this.getClass());
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
Log.i(TAG, "called onCreate");
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_main);
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_camera_view);
mOpenCvCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.i(TAG, "called onCreateOptionsMenu");
mItemSwitchCamera = menu.add("Toggle Native/Java camera");
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
String toastMesage = "";
Log.i(TAG, "called onOptionsItemSelected; selected item: " + item);
if (item == mItemSwitchCamera) {
mOpenCvCameraView.setVisibility(CameraBridgeViewBase.GONE);
mOpenCvCameraView.disableView();
mIsJavaCamera = !mIsJavaCamera;
if (mIsJavaCamera) {
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_camera_view);
toastMesage = "Java Camera";
} else {
mOpenCvCameraView = (CameraBridgeViewBase) findViewById(R.id.opencv_camera_view);
toastMesage = "Native Camera";
}
mOpenCvCameraView.setVisibility(CameraBridgeViewBase.VISIBLE);
mOpenCvCameraView.setCvCameraViewListener(this);
mOpenCvCameraView.enableView();
Toast.makeText(this, toastMesage, Toast.LENGTH_LONG).show();
}
return true;
}
@Override
public void onPause()
{
super.onPause();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
@Override
public void onResume()
{
super.onResume();
if (!OpenCVLoader.initDebug()) {
Log.d(TAG, "Internal OpenCV library not found. Using OpenCV Manager for initialization");
OpenCVLoader.initAsync(OpenCVLoader.OPENCV_VERSION_3_0_0, this, mLoaderCallback);
} else {
Log.d(TAG, "OpenCV library found inside package. Using it!");
mLoaderCallback.onManagerConnected(LoaderCallbackInterface.SUCCESS);
}
}
public void onDestroy() {
super.onDestroy();
if (mOpenCvCameraView != null)
mOpenCvCameraView.disableView();
}
public void onCameraViewStarted(int width, int height) {
mRgba = new Mat(height, width, CvType.CV_8UC4);
mGray = new Mat(height, width, CvType.CV_8UC1);
}
public void onCameraViewStopped() {
mRgba.release();
mGray.release();
}
public Mat onCameraFrame(CvCameraViewFrame inputFrame) {
mRgba = inputFrame.rgba();
mGray = inputFrame.gray();
// Convert to HSV color space
Mat hsv = new Mat();
Imgproc.cvtColor(mRgba, hsv, Imgproc.COLOR_RGB2HSV);
// Threshold the image to get only red pixels
Mat mask = new Mat();
Core.inRange(hsv, new Scalar(0, 70, 50), new Scalar(10, 255, 255), mask);
Core.inRange(hsv, new Scalar(170, 70, 50), new Scalar(180, 255, 255), mask);
Imgproc.GaussianBlur(mask, mask, new Size(9, 9), 2, 2);
// Find contours in the image
List<MatOfPoint> contours = new ArrayList<MatOfPoint>();
Imgproc.findContours(mask, contours, new Mat(), Imgproc.RETR_LIST, Imgproc.CHAIN_APPROX_SIMPLE);
// Find the largest contour
double maxArea = -1;
int maxAreaIdx = -1;
for (int idx = 0; idx < contours.size(); idx++) {
Mat contour = contours.get(idx);
double contourArea = Imgproc.contourArea(contour);
if (contourArea > maxArea) {
maxArea = contourArea;
maxAreaIdx = idx;
}
}
// If a contour was found, find the center of the contour
if (maxAreaIdx != -1) {
MatOfPoint largestContour = contours.get(maxAreaIdx);
Moments moments = Imgproc.moments(largestContour);
Point centroid = new Point();
centroid.x = moments.m10 / moments.m00;
centroid.y = moments.m01 / moments.m00;
// Draw a circle at the center of the contour
Imgproc.circle(mRgba, centroid, 10, new Scalar(0, 255, 0), -1);
}
return mRgba;
}
}
```
3. 在 res/layout 目录中创建一个名为 activity_main.xml 的布局文件,并将以下代码复制到其中:
```
<org.opencv.android.JavaCameraView
android:id="@+id/opencv_camera_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
```
4. 启动应用程序并使用设备的摄像头将交通灯置于摄像头的视野范围内,程序将识别并在交通灯中心绘制一个绿色的圆圈。
请注意,此示例程序仅识别红色交通灯。如果你要识别其他颜色的交通灯,你需要调整代码中的颜色阈值。
阅读全文