python - 如何在使用不同 np 形状的地方使用 np
问题描述
我想更有效地使用代码。
我现在通过参考图像形式的值来转换图像的颜色
很多人都知道,它与图像分割有关。
我通过深度学习模型得到了 Image [Width]*[Height] 的类值。
我想以原始颜色绘制分段区域,另一个以灰色绘制
下面是我的结果。人的部分是分割的区域
def read_video_frame(video_path):
cap = cv2.VideoCapture(video_path)
while(cap.isOpened()):
ret, frame = cap.read()
frame = cv2.resize(frame, dsize=(448, 448), interpolation=cv2.INTER_AREA)
image = np.array(frame)
mask = model_run(image) # Deep learning model
gray = skimage.color.gray2rgb(skimage.color.rgb2gray(image)) * 255
if mask is None:
segmented_image = gray.astype(np.uint8)
else:
segmented_image[:, :, 0] = np.where(mask >= 1, image[:, :, 0], gray[:, :, 0])
segmented_image[:, :, 1] = np.where(mask >= 1, image[:, :, 1], gray[:, :, 1])
segmented_image[:, :, 2] = np.where(mask >= 1, image[:, :, 2], gray[:, :, 2])
cv2.imshow('video', segmented_image)
if cv2.waitKey(1) & 0xff == ord('q'):
break
cap.release()
您会在图像中发现代码中令人不舒服的部分。
比如我通过一个深度学习模型得到(5*5)的类值
NumPy 数组的形式如下。
ex = np.array([[0,0,1,0,0],
[0,1,1,1,1],
[0,0,1,1,1],
[0,0,0,2,2],
[0,0,1,2,2]
])
如果数组的值大于1,则使用原始图像值,如果为0,则使用灰度图像值。
所以,我想用 np.where() 来一次处理它。
segmented_image[:, :] = np.where(mask >= 1, image[:, :], gray[:, :])
但我得到了这个错误
ValueError:操作数无法与形状一起广播 (448,448) (448,448,3) (448,448,3)
(我的目标图像尺寸是 448x448)
因为如您所知,图像像素的 NumPy 形状是 (width, height, 3)。
于是我被迫将r,g,b分成三个部分,形成一个图像。
segmented_image[:, :, 0] = np.where(mask >= 1, image[:, :, 0], gray[:, :, 0])
segmented_image[:, :, 1] = np.where(mask >= 1, image[:, :, 1], gray[:, :, 1])
segmented_image[:, :, 2] = np.where(mask >= 1, image[:, :, 2], gray[:, :, 2])
我怎样才能更清楚地编写代码?
解决方案
推荐阅读
- javascript - 使用 pg 和 postgresqlDB 在 node.js 中准备插入语句
- java -
错误的 在 Maven 中不工作 - c++ - VS 中的 UnitTest C++(预期值和实际值相同,但显示错误)
- node.js - 我有一个包含节点 js 包的 json 文件。如何对此类包进行安全审核?
- python - Gstreamer 警告:Gstreamer:管道尚未创建
- c++ - 是什么阻止了这段代码在 Visual C++ 6 中编译?
- docker - 无法通过 docker-compose 连接到我的 postgres 数据库
- amazon-s3 - 当我们将数据从加密的 AWS S3 存储桶发送到加密的 Google Cloud Storage 存储桶时,该数据是否在传输过程中加密?
- docker - 与 VM 的自托管代理相比,Docker 中的自托管 TFS 代理需要更长的时间来构建
- ios - 无法在 swift 中使用 iv 解密 AES256 数据,该数据由 nodeJS 使用 CBC 模式加密