img=cv2.threshold(image,90,255,cv2.THRESH_BINARY) #调整裁剪效果 阈值算法速度优于canny算法 # img = cv2.Canny(image,100,20) # cannyb = cv2.resize(b,None,fx=0.25,fy=0.25) # cv2.imshow('Canny', cannyb) # cv2.waitKey(0) binary_image=img[1] #二值图--具有三通道 # binary_image = img # binary_image=cv2.cvtColor(binary_image,cv2.COLOR_BGR2GRAY) # print(binary_image.shape) #改为单通道 x = binary_image.shape[1] print("宽度x=", x) y=binary_image.shape[0] print("高度y=",y) x_min = 0 y_min = 0 x_max = 0 y_max = 0 count = 0 for r in range(y): if 255 in binary_image[r][:]: if count == 0: y_min = r count += 1 y_max = r
时间: 2023-12-09 08:02:26 浏览: 147
以下是将该Python代码转换为C++代码的实现示例:
```c++
cv::Mat img;
cv::threshold(image, img, 90, 255, cv::THRESH_BINARY);
// cv::Canny(image, img, 100, 200);
// cv::resize(b, cannyb, cv::Size(), 0.25, 0.25);
// cv::imshow("Canny", cannyb);
// cv::waitKey(0);
cv::Mat binary_image = img;
// cv::cvtColor(binary_image, binary_image, cv::COLOR_BGR2GRAY);
// std::cout << binary_image.size() << std::endl;
int x = binary_image.cols;
std::cout << "宽度x=" << x << std::endl;
int y = binary_image.rows;
std::cout << "高度y=" << y << std::endl;
int x_min = 0, y_min = 0, x_max = 0, y_max = 0, count = 0;
for (int r = 0; r < y; r++) {
bool has_object = false;
for (int c = 0; c < binary_image.cols; c++) {
if (binary_image.at<uchar>(r, c) == 255) {
has_object = true;
break;
}
}
if (has_object) {
if (count == 0) {
y_min = r;
}
count++;
y_max = r;
}
}
```
需要注意的是,在C++中使用OpenCV库进行图像处理时,需要使用`cv::Mat`类型来表示图像,并且需要使用`at<uchar>(r, c)`方法来获取图像中指定位置的像素值。此外,在使用`cv::threshold()`函数时,需要将输出结果赋值给一个新的`cv::Mat`对象,而不能直接覆盖原始输入图像。
阅读全文