【发布时间】:2018-09-20 20:07:08
【问题描述】:
在图像中,我正在寻找轮廓,然后一次选择一个轮廓,然后修改每个轮廓。我只需要在这两条轮廓线之间反转区域的颜色。
import cv2
import numpy as np
import matplotlib.pyplot as plt
from skimage import io
%matplotlib inline
im = cv2.imread('bigO.jpg')
im = np.invert(im)
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
# plt.figure(figsize=(10,10))
# plt.imshow(imgray)
ret,thresh = cv2.threshold(imgray, 127,255,cv2.THRESH_BINARY)
image, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#Get any one contour
cnt = contours[1]
#Extend the contour
def rand_xy(mu, sigma):
return np.random.normal(mu, sigma), np.random.normal(mu, sigma)
cnt_new = np.asarray([point + rand_xy(mu = 5., sigma = 0.5) for point in cnt], dtype=np.int32)
#DRAW CONTOURS
cv2.drawContours(im, cnt, -1, (255, 0, 0), 1)
cv2.drawContours(im, cnt_new, -1, (255, 0, 0), 1)
plt.figure(figsize=(10,10))
plt.imshow(im)
#Here I need to invert the color of images between the contours.
预期输出:
预期的是在两个轮廓之间像素倒置的整个图像。
【问题讨论】:
-
如果您的图像是二进制 (uint8) 并且您想要反转它,为什么不直接应用
cv2.bitwise_not(im)呢? -
OP 是只在两个轮廓之间而不是整个图像之间反转颜色。添加了一张图片以使问题更清楚
-
1.制作蒙版:在新的空白图像上标记轮廓之间的空间,使其在轮廓之间为黑色,否则为白色(可能更容易绘制相反的然后反转蒙版)。 2. 使用该新蒙版选择反转颜色的位置,方法是将其作为
cv2.bitwise_not(img, mask=...)中的mask参数传递。这将翻转img中像素的颜色,仅在您的蒙版中它们为白色(非零)的位置。