def frame_processing(frame):
out_frame = np.zeros((frame.shape[0],frame.shape[1],4),dtype = np.uint8)
b,g,r = cv2.split(frame)
alpha = np.zeros_like(b , dtype=np.uint8)
print(out_frame.shape)
print(b.shape);print(g.shape);print(r.shape);print(alpha.shape)
for i in range(frame.shape[0]):
for j in range(frame.shape[1]):
a = (frame[i,j,0],frame[i,j,1],frame[i,j,2])
b = (225,225,225)
if all(i > j for i, j in zip(a,b)): #all(a>b) :
alpha[i,j] = 0
else:
alpha[i,j] = 255
out_frame[:,:,0] = b
out_frame[:,:,1] = g
out_frame[:,:,2] = r
out_frame[:,:,3] = alpha
#out_frame = cv2.merge((b,g,r,alpha))
return out_frame
Wanted to add an alpha channel; tried cv2.Merge()
and manual stacking of channels but failed.
When using cv2.merge()
:
error: OpenCV(3.4.2) C:\projects\opencv-
python\opencv\modules\core\src\merge.cpp:458: error: (-215:Assertion failed)
mv[i].size == mv[0].size && mv[i].depth() == depth in function 'cv::merge'
When manually adding channels:
ValueError: could not broadcast input array from shape (3) into shape
(225,225)
Use cv2.inRange
to find the mask, then merge them with np.dstack
:
#!/use/bin/python3
# 2018/09/24 11:51:31 (CST)
import cv2
import numpy as np
#frame = ...
mask = cv2.inRange(frame, (225,225,225), (255,255,255))
#dst = np.dstack((frame, 255-mask))
dst = np.dstack((frame, mask))
cv2.imwrite("dst.png", dst)
To find the specific color, maybe you will be interested with this question:
Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)
Its a simple typo. You are changing the variable "b" in the for loop and it conflicts with variable of blue channel. Change b = (225,225,225)
to threshold = (225, 255, 255)
and zip(a,b)
to zip(a, threshold)
should fix the problem.
By the way, you can use this to create your alpha channel:
alpha = np.zeros(b.shape, dtype=b.dtype)
Also you can fill your alpha channel like this if you need more speed (you can measure time difference):
alpha[~((b[:,:]>threshold[0]) & (g[:,:]>threshold[1]) & (r[:,:]>threshold[2]))] = 255
So your function becomes:
def frame_processing(frame):
# split channels
b,g,r = cv2.split(frame)
# initialize alpha to zeros
alpha = np.zeros(b.shape, dtype=b.dtype)
# fill alpha values
threshold = (225, 225, 225)
alpha[~((b[:,:]>threshold[0]) & (g[:,:]>threshold[1]) & (r[:,:]>threshold[2]))] = 255
# merge all channels back
out_frame = cv2.merge((b, g, r, alpha))
return out_frame
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.