我已经阅读了documentation for copyTo(),但是对于如何将此函数应用于以下代码仍然感到困惑。 This anwer指出我们可以使用copyTo函数而不是255-x。在这种情况下如何应用此功能?我希望您能看到一段代码。
# Compute the gradient map of the image
def doLap(image):
# YOU SHOULD TUNE THESE VALUES TO SUIT YOUR NEEDS
kernel_size = 5 # Size of the laplacian window
blur_size = 5 # How big of a kernal to use for the gaussian blur
# Generally, keeping these two values the same or very close works well
# Also, odd numbers, please...
blurred = cv2.GaussianBlur(image, (blur_size,blur_size), 0)
return cv2.Laplacian(blurred, cv2.CV_64F, ksize=kernel_size)
#
# This routine finds the points of best focus in all images and produces a merged result...
#
def focus_stack(unimages):
images = align_images(unimages)
print "Computing the laplacian of the blurred images"
laps = []
for i in range(len(images)):
print "Lap {}".format(i)
laps.append(doLap(cv2.cvtColor(images[i],cv2.COLOR_BGR2GRAY)))
laps = np.asarray(laps)
print "Shape of array of laplacians = {}".format(laps.shape)
output = np.zeros(shape=images[0].shape, dtype=images[0].dtype)
abs_laps = np.absolute(laps)
maxima = abs_laps.max(axis=0)
bool_mask = abs_laps == maxima
mask = bool_mask.astype(np.uint8)
for i in range(0,len(images)):
output = cv2.bitwise_not(images[i],output, mask=mask[i])
return 255-output
答案 0 :(得分:2)
对不起,我在那儿误导了你。尽管它在C ++中能很好地工作,但我在Python中找不到绑定。但是,您可以使用numpy.copyto函数。
这是一个小示例,演示了两种方法(bitwise_not
和copyto
)产生的结果相同。
import cv2
import numpy as np
# Create two images
im1 = np.zeros((100, 100, 3), np.uint8)
im1[:] = (255, 0, 0)
im2 = np.zeros((100, 100, 3), np.uint8)
im2[:] = (0, 255, 0)
# Generate a random mask
ran = np.random.randint(0, 2, (100, 100), np.uint8)
# List of images and masks
images = [im1, im2]
mask = [ran, 1-ran]
not_output = np.zeros((100, 100, 3), np.uint8)
copy_output = np.zeros((100, 100, 3), np.uint8)
for i in range(0, len(images)):
# Using the 'NOT' way
not_output = cv2.bitwise_not(images[i], not_output, mask=mask[i])
# Using the copyto way
np.copyto(copy_output, images[i], where=mask[i][:, :, None].astype(bool))
cv2.imwrite('not.png', 255 - not_output)
cv2.imwrite('copy.png', copy_output)
请注意,在遮罩数组中填充了额外的尺寸,以便可以广播。