我的图像边缘有不同深浅的黑色,中心有一点红色。我想使用 opencv 将所有黑色像素转换为透明像素。我是 opencv 的新手,非常感谢您的帮助。
我尝试按照 fireant 在链接中所说的进行操作:overlay a smaller image on a larger image python OpenCv ,但它没有用。这是我到目前为止的代码:
img = cv2.imread("/home/uwatt/Downloads/lensf1.jpg")
img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)
tmp = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
_,alpha = cv2.threshold(tmp,5,255,cv2.THRESH_BINARY)
b,g,r = cv2.split(img)
rgba = [b,g,r,alpha]
dst = cv2.merge(rgba, 4)
plt.imshow(dst)
print(dst.shape)
face_cascade = cv2.CascadeClassifier('/home/uwatt/DIP/lensflare/haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('/home/uwatt/DIP/lensflare/haarcascade_eye.xml')
user = cv2.imread("/home/uwatt/Downloads/Dicaprio.jpg")
gray_user = cv2.cvtColor(user, cv2.COLOR_BGR2GRAY)
user = cv2.cvtColor(user, cv2.COLOR_BGR2BGRA)
faces = face_cascade.detectMultiScale(gray_user, 1.3, 5)
print("Faces:",faces)
for (x,y,w,h) in faces:
roi_gray = gray_user[y:y+h,x:x+w]
roi_color = user[y:y+h,x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
print(ex,ey,ew,eh)
#cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,0,255),5)
# resizing & paste the lf image on user
roi_eye = user[y+ey:y+ey+eh,x+ex:x+ex+ew]
resized_lensflare = cv2.resize(dst,(eh,ew))
resized_lensflare = cv2.cvtColor(resized_lensflare, cv2.COLOR_BGR2RGBA)
user[y+ey:y+ey+eh,x+ex:x+ex+ew] = resized_lensflare
您需要使用 alpha 混合将镜头光晕与背景图像结合起来。查看this tutorial to find out more about alpha blending.这是我使用的脱衣舞:
import cv2
flare = cv2.imread("/home/stephen/Desktop/flare.jpg")
user = cv2.imread("/home/stephen/Desktop/leo.jpg")
eyes = [[100,50,200,200],[175,50,200,200]]
for x,y,w,h in eyes:
# resizing & paste the lf image on user
roi_eye = user[y:y+h,x:x+w]
resized_lensflare = cv2.resize(flare,(w,h))
# Make foreground background and alpha
foreground = resized_lensflare.copy()
background = roi_eye.copy()
alpha= foreground.copy()
# Convert uint8 to float
foreground = foreground.astype(float)
background = background.astype(float)
# Normalize the alpha mask to keep intensity between 0 and 1
alpha = alpha.astype(float)/255
# Multiply the foreground with the alpha matte
foreground = cv2.multiply(alpha, foreground)
# Multiply the background with ( 1 - alpha )
background = cv2.multiply(1.0 - alpha, background)
# Add the masked foreground and background.
outImage = cv2.add(foreground, background)
# Mask the user image
user[y:y+h,x:x+w] = outImage
cv2.imshow('img', user)
cv2.waitKey()
cv2.destroyAllWindows()
我是一名优秀的程序员,十分优秀!