使用opencv python在图像上绘制网格线

1 python opencv

使用 OpenCV python,我想在打开相机时制作一个网格。你们能帮我提供逻辑或代码吗?请找到下面的图片链接以便更好地理解。

相机打开并指向地板

网格线在整个图像上分开

And*_*dyP 11

这是创建 mxn 网格的简单解决方案:

import cv2 as cv  # tested with version 4.5.3.56 (pip install opencv-python)
import numpy as np


def draw_grid(img, grid_shape, color=(0, 255, 0), thickness=1):
    h, w, _ = img.shape
    rows, cols = grid_shape
    dy, dx = h / rows, w / cols

    # draw vertical lines
    for x in np.linspace(start=dx, stop=w-dx, num=cols-1):
        x = int(round(x))
        cv.line(img, (x, 0), (x, h), color=color, thickness=thickness)

    # draw horizontal lines
    for y in np.linspace(start=dy, stop=h-dy, num=rows-1):
        y = int(round(y))
        cv.line(img, (0, y), (w, y), color=color, thickness=thickness)

    return img
Run Code Online (Sandbox Code Playgroud)

下面是一个将此函数封装在 CLI 中的脚本: https://gist.github.com/mathandy/389ddbad48810d188bdc997c3a1dab0c


小智 5

这是我的问题的解决方案。好好利用它。

import matplotlib.pyplot as plt
import matplotlib.ticker as plticker
try:
    from PIL import Image
except ImportError:
    import Image

# Open image file
image = Image.open('bird.jpg')
my_dpi=200.

# Set up figure
fig=plt.figure(figsize=(float(image.size[0])/my_dpi,float(image.size[1])/my_dpi),dpi=my_dpi)
ax=fig.add_subplot(111)

# Remove whitespace from around the image
fig.subplots_adjust(left=0,right=1,bottom=0,top=1)

# Set the gridding interval: here we use the major tick interval
myInterval=300.
loc = plticker.MultipleLocator(base=myInterval)
ax.xaxis.set_major_locator(loc)
ax.yaxis.set_major_locator(loc)

# Add the grid
ax.grid(which='major', axis='both', linestyle='-', color='g')

# Add the image
ax.imshow(image)

# Find number of gridsquares in x and y direction
nx=abs(int(float(ax.get_xlim()[1]-ax.get_xlim()[0])/float(myInterval)))
ny=abs(int(float(ax.get_ylim()[1]-ax.get_ylim()[0])/float(myInterval)))




# Save the figure
fig.savefig('birdgrid_without_Label.jpg')
Run Code Online (Sandbox Code Playgroud)

上述代码的输出