我试图运行一些Convex Hull图像处理。基本上我想做的是关闭一个开放的轮廓。
我找到this answer over at the opencv forum,这正是我想要做的。我不久前开始将代码从C ++转换为Python。我成功地转换了问题的代码,但答案的代码给了我比预期更艰难的时间。
这是我到目前为止所做的:
import cv2
import numpy as np
def contoursConvexHull(contours):
print("contours length = ", len(contours))
print("contours length of first item = ", len(contours[1]))
pts = []
for i in range(0, len(contours)):
for j in range(0, len(contours[i])):
pts.append(contours[i][j])
result = cv2.convexHull(pts)
return result
# Get our image in color mode (1)
src = cv2.imread("source.png", 1);
# Convert the color from BGR to Gray
srcGray = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY)
# Use Gaussian Blur
srcBlur = cv2.GaussianBlur(srcGray, (3, 3), 0)
# ret is the returned value, otsu is an image
ret, otsu = cv2.threshold(srcBlur, 0, 255,
cv2.THRESH_BINARY+cv2.THRESH_OTSU)
# Use canny
srcCanny = cv2.Canny(srcBlur, ret, ret*2, 3)
# im is the output image
# contours is the contour list
# I forgot what heirarchy was
im, contours, heirarchy = cv2.findContours(srcCanny,
cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(src, contours, -1, (0, 255, 0), 3)
ConvexHullPoints = contoursConvexHull(contours)
cv2.polylines(src, [ConvexHullPoints], True, (0, 255, 255), 2)
cv2.imshow("Test", src)
cv2.waitKey(0)
当我试图运行它时,它会给我
result = cv2.convexHull(pts)
TypeError: points is not a numpy array, neither a scalar
而且我猜测我正在为convexHull
提供输入,而它还需要其他东西。
我在C ++方面相当不错,但我是Python的初学者。我想我可能做错了我将轮廓元素附加到pts
列表?
老实说,我不太清楚为什么我们需要将这些点追加到一个新阵列中,似乎没有任何价值操纵或重新排列。
这里是C ++代码供参考:
#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/highgui/highgui.hpp"
#include <stdlib.h>
#include <stdio.h>
using namespace cv;
using namespace std;
vector<Point> contoursConvexHull( vector<vector<Point> > contours )
{
vector<Point> result;
vector<Point> pts;
for ( size_t i = 0; i< contours.size(); i++)
for ( size_t j = 0; j< contours[i].size(); j++)
pts.push_back(contours[i][j]);
convexHull( pts, result );
return result;
}
int main( int, char** argv )
{
Mat src, srcGray,srcBlur,srcCanny;
src = imread( argv[1], 1 );
cvtColor(src, srcGray, CV_BGR2GRAY);
blur(srcGray, srcBlur, Size(3, 3));
Canny(srcBlur, srcCanny, 0, 100, 3, true);
vector<vector<Point> > contours;
findContours( srcCanny, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_SIMPLE );
Mat drawing = Mat::zeros(srcCanny.size(), CV_8UC3);
for (int i = 0; i< contours.size(); i++)
{
Scalar color = Scalar( 255,255,255);
drawContours( drawing, contours, i, color, 2 );
}
vector<Point> ConvexHullPoints = contoursConvexHull(contours);
polylines( drawing, ConvexHullPoints, true, Scalar(0,0,255), 2 );
imshow("Contours", drawing);
polylines( src, ConvexHullPoints, true, Scalar(0,0,255), 2 );
imshow("contoursConvexHull", src);
waitKey();
return 0;
}
答案 0 :(得分:1)
错误说pts
不是一个numpy数组;它是一个python list
。
要将pts
转换为数组,请导入numpy并执行简单转换:
import numpy as np
# code ....
pts = np.array(pts)
result = cv2.convexHull(pts)