0
我正在嘗試運行一些凸面圖像處理。基本上我想要做的是關閉一個開放的輪廓。我發現this answer over at the opencv forum,這正是我想要做的。前段時間我開始將代碼從C++轉換爲Python。我成功地轉換了問題的代碼,但答案的代碼給了我比預期更加艱難的時間。Python OpenCV - ConvexHull錯誤「點不是一個numpy數組,不是一個標量」?
這是我到目前爲止有: 進口CV2 進口numpy的爲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++轉換爲Python,我將不勝感激。
下面是參考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;
}
到目前爲止是這種情況,以使代碼的運行。但是,我仍然沒有得到我期望的結果。 – Razgriz
多數民衆贊成在技巧,但希望我回答你的原始問題。您可以更新您的問題以反映新問題。實際上,可以考慮提出一個新問題。 – putonspectacles
我明白了,我只是用方括號括起'ConvexHullPoints',代碼按預期工作。 – Razgriz