在图像上找到特定点

时间:2019-02-13 02:53:57

标签: python image opencv

我正在尝试编写一个解决难题的程序。我的尝试与我要测试的示例拼图很好地配合使用。现在,我想为一个实际的难题做一个。 这个新拼图的拼图碎片实际上并没有合适的形状。

puzzle piece

我设法使图像变成黑白,最后变成1和0的数组,其中1表示块,0表示背景。我想找到一种方法来识别这些碎片的四个角,峰和深度的坐标。

points

我试图计算靠近1的0的数量,以查看边框中的最大曲线。但是形状不够平滑,无法正常工作。

counter = np.zeros((lenX,lenY),dtype=int)
for i in range(lenX):
    for j in range(lenY):
        if img[i,j]==1:
            counter[i,j] = count_white(img,i,j,lenX,lenY)

print(counter)
tpath = os.getcwd()+"/test.jpg"
print(cv2.imwrite(tpath, Image))
print("saved at : ",tpath)
np.savetxt("test.csv", counter, delimiter=",")

def count_white(img,x,y,lenX,lenY):
    X = [x-1,x,x+1,x+1,x+1,x,x-1,x-1]
    Y = [y-1,y-1,y-1,y,y+1,y+1,y+1,y]
    count = 0
    for i in range(len(X)):
        if X[i] < lenX and Y[i] < lenY:
            if img[X[i],Y[i]] == 0:
                count=count+1
    return count

有任何建议,参考或想法吗?

1 个答案:

答案 0 :(得分:1)

抱歉,C ++代码适用于您的情况:

cv::Mat gray = cv::imread("Sq01a.png", cv::IMREAD_GRAYSCALE);

gray = 255 - gray;


cv::Mat bin;
cv::threshold(gray, bin, 1, 255, cv::THRESH_BINARY);

cv::Mat bigBin(2 * bin.rows, 2 * bin.cols, CV_8UC1, cv::Scalar(0));
bin.copyTo(cv::Mat(bigBin, cv::Rect(bin.cols / 2, bin.rows / 2, bin.cols, bin.rows)));


std::vector<std::vector<cv::Point> > contours;
cv::findContours(bigBin, contours, cv::RETR_EXTERNAL, cv::CHAIN_APPROX_NONE);

if (contours.size() > 0)
{
    std::vector<cv::Point> tmp = contours[0];
    const cv::Point* elementPoints[1] = { &tmp[0] };
    int numberOfPoints = (int)tmp.size();
    cv::fillPoly(bigBin, elementPoints, &numberOfPoints, 1, cv::Scalar(255, 255, 255), 8);
}

int maxCorners = 20;
double qualityLevel = 0.01;
double minDistance = bigBin.cols / 8;
int blockSize = 5;
bool useHarrisDetector = true;
double k = 0.04;
std::vector<cv::Point2f> corners;
cv::goodFeaturesToTrack(bigBin, corners, maxCorners, qualityLevel, minDistance, cv::noArray(), blockSize, useHarrisDetector, k);

std::vector<cv::Point2f> resCorners;
std::vector<cv::Point2f> imgCorners = { cv::Point2f(0, 0), cv::Point2f(bigBin.cols, 0), cv::Point2f(bigBin.cols, bigBin.rows), cv::Point2f(0, bigBin.rows) };
for (auto imgCorn : imgCorners)
{
    size_t best_i = corners.size();
    float min_dist = bigBin.cols * bigBin.rows;
    for (size_t i = 0; i < corners.size(); ++i)
    {
        float dist = cv::norm(imgCorn - corners[i]);
        if (dist < min_dist)
        {
            best_i = i;
            min_dist = dist;
        }
    }
    if (best_i != corners.size())
    {
        resCorners.push_back(corners[best_i]);
    }
}
cv::Mat bigColor;
cv::cvtColor(bigBin, bigColor, cv::COLOR_GRAY2BGR);
for (auto corner : corners)
{
    cv::circle(bigColor, corner, 10, cv::Scalar(0, 0, 255.), 1);
}
for (auto corner : resCorners)
{
    cv::circle(bigColor, corner, 5, cv::Scalar(0, 255, 0), 2);
}

cv::imshow("gray", gray);
cv::imshow("bigColor", bigColor);
cv::waitKey(0);

这里是红色圆圈-哈里斯(Harris)的角和绿色-与图像角点最近的角。可以吗?

Result: