import cv2import numpy as np# center定义center = 320 # 打开摄像头图像尺寸640480长高opencv存储值为480640行列cap = cv2VideoCapture0while 1 ret frame = capread # 转化为灰度图 if ret == False # 如果是最后一帧这个值为False br
#include
using namespace std; using namespace cv;
int main() { int center = 320;
VideoCapture cap(0);
if (!cap.isOpened())
{
cout << "error: cannot open camera" << endl;
return -1;
}
while (true)
{
Mat frame;
cap >> frame;
if (frame.empty())
{
cout << "end of video" << endl;
break;
}
Mat gray, dst;
cvtColor(frame, gray, COLOR_BGR2GRAY);
threshold(gray, dst, 0, 255, THRESH_OTSU);
dilate(dst, dst, Mat(), Point(-1, -1), 2);
Mat color = dst.row(400);
int white_count = countNonZero(color == 0);
int white_count_judge = countNonZero(color == 255);
if (white_count_judge == 640)
{
cout << "no black pixels" << endl;
}
else
{
vector<int> white_index;
findNonZero(color == 0, white_index);
if (white_count == 0)
{
white_count = 1;
}
float center = (white_index[0] + white_index[white_count - 1]) / 2.0;
float direction = center - 320;
cout << "direction: " << direction << endl;
}
imshow("dst", dst);
if (waitKey(1) == 'q')
{
break;
}
}
cap.release();
destroyAllWindows();
return 0;
原文地址: https://www.cveoy.top/t/topic/gTES 著作权归作者所有。请勿转载和采集!