基于拐角的OpenCV C++作物图像

2024-09-28 01:30:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我问了一个类似的问题,但是对于使用numpy数组Opencv Python Crop Image Using Numpy Array的python来说。我正在寻找一个基于它的角落图像裁剪。这里展示的是一张照片。 Cropping Goal

我有Python代码,但需要转换成C++。下面是我的工作Python代码和部分C++代码。在

def crop(self,image):
    grayed = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
    (_,thresh) = cv2.threshold(grayed,1,255,cv2.THRESH_BINARY)
    result, contours, _= cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    x, y = [], []
    for i in range(len(contours)):
        for j in range(len(contours[i])):
            x.append(contours[i][j][0][0])
            y.append(contours[i][j][0][1])
    x1, x2, y1, y2 = min(x), max(x), min(y), max(y)
    cropped = image[y1:y2, x1:x2]
    return cropped

C++代码:

^{pr2}$

Tags: 代码inimageforlenrangecv2x1
2条回答
cv::Mat crop(cv::Mat image){
  cv::Mat cropped, grayed, thresh, result;
  std::vector < std::vector < cv::Point >> contours;
  std::vector<cv::Vec4i> hierarchy;
  cvtColor(image, grayed, cv::COLOR_BGR2GRAY);
  threshold(grayed, thresh, 1, 255, cv::THRESH_BINARY);
  findContours(result, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, cv::Point(0, 0));
  std::vector<int> x, y;

  for (int i = 0; i < contours.size(); i++){
      for (int j = 0; j <= contours.at(i).size(); j++){
          x.push_back(contours.at(i).at(j).x);
          y.push_back(contours.at(i).at(j).y);
      }
  }
  int x1 = std::min_element(x.begin(), x.end());
  int x2 = std::max_element(x.begin(), x.end());
  int y1 = std::min_element(y.begin(), y.end());
  int y2 = std::max_element(y.begin(), y.end())

  cv::Rect rect(x1, y1, x2 - x1, y2 - y1);
  cropped = image(rect);

  return cropped;
}

试试这个

Mat crop(Mat image){
Mat cropped, grayed, thresh, result;
vector<vector<Point>> contours;
vector<Vec4i> hierarchy;
cvtColor(image, grayed, CV_BGR2GRAY);
threshold( grayed, thresh, 1, 255,THRESH_BINARY);
findContours( thresh, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE);

vector<int> x,y;
for(int i=0; i < contours.size();i++){
    for(int j = 0; j < contours.at(i).size();j++){
        x.push_back(contours[i][j].x);
        y.push_back(contours[i][j].y);
    }
}

auto xVals = std::minmax_element(x.begin(), x.end());
auto yVals = std::minmax_element(y.begin(), y.end());

Rect rect (*xVals.first,*yVals.first,(*xVals.second)-(*xVals.first),(*yVals.second)-(*yVals.first));
cropped = image(rect);
return cropped;

}

相关问题 更多 >

    热门问题