簡體   English   中英

使用 OpenCV Python 在圖像上繪制網格線

[英]Drawing grid lines across the image using OpenCV Python

使用 OpenCV python,我想在打開相機時制作一個網格。 你們能幫我一個邏輯或代碼嗎? 請找到下面的圖片鏈接以更好地理解。

相機打開並指向地板

網格線在整個圖像中分割

這是我的問題的解決方案。 好好利用它。

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')

上述代碼的輸出

def draw_grid(img, line_color=(0, 255, 0), thickness=1, type_=_cv2.LINE_AA, pxstep=50):
    '''(ndarray, 3-tuple, int, int) -> void
    draw gridlines on img
    line_color:
        BGR representation of colour
    thickness:
        line thickness
    type:
        8, 4 or cv2.LINE_AA
    pxstep:
        grid line frequency in pixels
    '''
    x = pxstep
    y = pxstep
    while x < img.shape[1]:
        _cv2.line(img, (x, 0), (x, img.shape[0]), color=line_color, lineType=type_, thickness=thickness)
        x += pxstep

    while y < img.shape[0]:
        _cv2.line(img, (0, y), (img.shape[1], y), color=line_color, lineType=type_, thickness=thickness)
        y += pxstep

您可以使用cv2.line()函數在輸入圖像上繪制線條。 因此,根據您要繪制線條的位置,您的基本代碼將如下所示:

img = cv2.imread(r"path\to\img")
cv2.line(img, (start_x, start_y), (end_x, end_y), (255, 0, 0), 1, 1)

要獲取圖像的尺寸,您可以使用將返回(height, width)img.shape

例如,要通過中心繪制一條垂直線,您的代碼將如下所示:

cv2.line(img, (int(img.shape[1]/2), 0),(int(img.shape[1]/2), img.shape[0]), (255, 0, 0), 1, 1)

這是創建 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

這是在 CLI 中包裝此函數的腳本: https ://gist.github.com/mathandy/389ddbad48810d188bdc997c3a1dab0c

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM