如何让openCV检测我制作的这个棋盘?

xoefb8l8  于 2023-02-13  发布在  其他
关注(0)|答案(1)|浏览(172)

我试过在open CV python中使用findChessboardCorners函数。但是它不起作用。这些是我试图让它检测这些图像的图像。
board.jpg

board2.jpg

我希望它能够检测方块的位置以及方块上是否有棋子。
目前为止我试过

import cv2 as cv
import numpy as np

def rescaleFrame(frame, scale=0.75):
    #rescale image
    width = int(frame.shape[1] * scale)
    height = int(frame.shape[0] * scale)

    dimensions = (width,height)

    return cv.resize(frame, dimensions, interpolation=cv.INTER_AREA)

img = cv.imread("board2.jpg")
gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)

ret, corners = cv.findChessboardCorners(gray, (8,8),None)

if ret == True:
   
   # Draw and display the corners
   img = cv.drawChessboardCorners(img, (8,8), corners,ret)

img=rescaleFrame(img)
cv.imshow("board",img)
v.waitKey(0)

I was expect it to work like how this tutorial shows

hs1ihplo

hs1ihplo1#

函数findChessboardCorners用于使用白色棋盘图案校准相机。据我所知,它不是设计用于检测棋盘上有棋子的角落。
此站点显示了calibration "chess boards."的示例。this site显示了如何使用这些校准棋盘,此示例使用ROS库。
你仍然可以使用OpenCV,但需要尝试其他功能。假设你自己拍了照片,你也让自己的问题更难,因为你使用了一个有很多线和角的背景,这意味着你必须区分这些角和棋盘上的角。你还可以看到车后面的棋盘顶角被遮挡了。如果你可以重拍照片,我会拍一张自上而下的照片,在一个空白的表面上与棋盘形成对比。
OpenCV中角点检测的一个例子是Harris角点检测。我为你写了一个简短的例子。你需要尝试一下这个和其他角点检测方法,看看哪种效果最好。我发现添加一个索贝尔滤波器来增强图像中的线条会得到更好的结果。但是它仍然会检测到背景中的角点和棋子上的角点。你可以用它来检测角点。我需要弄清楚如何过滤掉这些。

import cv2 as cv
from matplotlib import pyplot as plt
import numpy as np

def sobel(src_image, kernel_size):
    grad_x = cv.Sobel(src_image, cv.CV_16S, 1, 0, ksize=kernel_size, scale=1,
                      delta=0, borderType=cv.BORDER_DEFAULT)
    grad_y = cv.Sobel(src_image, cv.CV_16S, 0, 1, ksize=kernel_size, scale=1, 
                      delta=0, borderType=cv.BORDER_DEFAULT)
    abs_grad_x = cv.convertScaleAbs(grad_x)
    abs_grad_y = cv.convertScaleAbs(grad_y)

    grad = cv.addWeighted(abs_grad_x, 0.5, abs_grad_y, 0.5, 0)

    return grad

def process_image(src_image_path):
    # load the image
    src_image = cv.imread(src_image_path)
    # convert to RGB (otherwise when you display this image the colors will look incorrect)
    src_image = cv.cvtColor(src_image, cv.COLOR_BGR2RGB)
    # convert to grayscale before attempting corner detection
    src_gray = cv.cvtColor(src_image, cv.COLOR_BGR2GRAY)

    # standard technique to eliminate noise
    blur_image = cv.blur(src_gray,(3,3))

    # strengthen the appearance of lines in the image
    sobel_image = sobel(blur_image, 3)

    # detect corners
    corners = cv.cornerHarris(sobel_image, 2, 3, 0.04)
    # for visualization to make corners easier to see
    corners = cv.dilate(corners, None)

    # overlay on a copy of the source image
    dest_image = np.copy(src_image)
    dest_image[corners>0.01*corners.max()]=[0,0,255]
    return dest_image 

src_image_path = "board1.jpg"
dest_image = process_image(src_image_path)
plt.imshow(dest_image)
plt.show()

相关问题