1 px 粗线 cv2
1 px thick line cv2
我需要在图像中画一条线,其中水平方向上没有像素的宽度大于 1 个像素。
尽管我在折线中使用 thickness=1,
cv2.polylines(img, np.int32([points]), isClosed=False, color=(255, 255, 255), thickness=1)
在生成的图中可能有 2 个水平相邻像素设置为 255,如下图所示:
如何防止相邻像素设置为 255?或者等价地:将 2 之一设置为 0 的有效方法是什么?
我想到了侵蚀,但是在那些只有 1255 像素的行中,这样的像素也将设置为 0。
看来我们需要使用 for 循环。
从两个水平相邻像素中删除一个像素是一种迭代操作。
我看不到对其进行矢量化或使用过滤或形态学操作的方法。
可能有一些我遗漏的东西,但我认为我们需要使用循环。
如果图片较大,可以使用Numba (or Cython)加快执行时间
import cv2
import numpy as np
from numba import jit
@jit(nopython=True) # Use Numba JIT for accelerating the code execution time
def horiz_skip_pix(im):
for y in range(im.shape[0]):
for x in range(1, im.shape[1]):
# Use logical operation instead of using "if statement".
# We could have used an if statement, like if im[y, x]==255 and im[y, x-1]==255: im[y, x] = 0 ...
im[y, x] = im[y, x] & (255-im[y, x-1])
# Build sample input image
src_img = np.zeros((10, 14), np.uint8)
points = np.array([[2,2], [5,8], [12,5], [12,2], [3, 2]], np.int32)
cv2.polylines(src_img, [points], isClosed=False, color=(255, 255, 255), thickness=1)
dst_img = src_img.copy()
# Remove horizontally adjacent pixels.
horiz_skip_pix(dst_img)
# Show result
cv2.imshow('src_img', cv2.resize(src_img, (14*20, 10*20), interpolation=cv2.INTER_NEAREST))
cv2.imshow('dst_img', cv2.resize(dst_img, (14*20, 10*20), interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
cv2.destroyAllWindows()
src_img
:
dst_img
:
我不会将结果称为“1 px 粗线”,但它符合“防止相邻像素”的条件。
我需要在图像中画一条线,其中水平方向上没有像素的宽度大于 1 个像素。
尽管我在折线中使用 thickness=1,
cv2.polylines(img, np.int32([points]), isClosed=False, color=(255, 255, 255), thickness=1)
在生成的图中可能有 2 个水平相邻像素设置为 255,如下图所示:
如何防止相邻像素设置为 255?或者等价地:将 2 之一设置为 0 的有效方法是什么?
我想到了侵蚀,但是在那些只有 1255 像素的行中,这样的像素也将设置为 0。
看来我们需要使用 for 循环。
从两个水平相邻像素中删除一个像素是一种迭代操作。
我看不到对其进行矢量化或使用过滤或形态学操作的方法。
可能有一些我遗漏的东西,但我认为我们需要使用循环。
如果图片较大,可以使用Numba (or Cython)加快执行时间
import cv2
import numpy as np
from numba import jit
@jit(nopython=True) # Use Numba JIT for accelerating the code execution time
def horiz_skip_pix(im):
for y in range(im.shape[0]):
for x in range(1, im.shape[1]):
# Use logical operation instead of using "if statement".
# We could have used an if statement, like if im[y, x]==255 and im[y, x-1]==255: im[y, x] = 0 ...
im[y, x] = im[y, x] & (255-im[y, x-1])
# Build sample input image
src_img = np.zeros((10, 14), np.uint8)
points = np.array([[2,2], [5,8], [12,5], [12,2], [3, 2]], np.int32)
cv2.polylines(src_img, [points], isClosed=False, color=(255, 255, 255), thickness=1)
dst_img = src_img.copy()
# Remove horizontally adjacent pixels.
horiz_skip_pix(dst_img)
# Show result
cv2.imshow('src_img', cv2.resize(src_img, (14*20, 10*20), interpolation=cv2.INTER_NEAREST))
cv2.imshow('dst_img', cv2.resize(dst_img, (14*20, 10*20), interpolation=cv2.INTER_NEAREST))
cv2.waitKey()
cv2.destroyAllWindows()
src_img
:
dst_img
:
我不会将结果称为“1 px 粗线”,但它符合“防止相邻像素”的条件。