[英]How can I replace `plt.imsave` with `cmap` option set to `gray` with opencv operations?
這是我正在使用的源圖像:
我正在使用這個github 存儲庫(我使用的文件是tools/test_lanenet.py
)來進行二進制車道分割。 現在我得到了這張圖片:
第二個圖像實際上是由這個命令產生的圖像:
# this line results in an array with the shape of (512, 256). this is just a hypothetical line of code. what I really care is the line which saves the image with matplotlib library.
binary_seg_image = lane_segmenter.binary_segment()
# this line saves the image
plt.imsave('binary_image_plt.png', binary_seg_image[0] * 255, cmap='gray')
首先,我必須對 opencv 模塊執行相同的操作,最好更快。
在接下來的操作中,我必須將第二幅圖像中分割的車道映射到源圖像道路車道上。 我想我必須使用第二張圖像作為掩碼並使用cv2.bitwise_and
來做工作嗎? 有誰能夠幫助我?
謝謝你們
如果您想為蒙版存在的圖像着色,那么這是使用 Python/OpenCV 的一種方法。 代替 bitwise_and,您只需在蒙版為白色的地方進行 numpy 着色。 再次注意,您的圖像大小不同,我不知道如何最好地對齊它們。 我把它留給你。 我正在使用您的兩個輸入圖像,就像我的其他答案一樣。 代碼幾乎相同。
import cv2
import numpy as np
# read image
img = cv2.imread('road.png')
ht, wd, cc = img.shape
print(img.shape)
# read mask as grayscale
gray = cv2.imread('road_mask.png', cv2.IMREAD_GRAYSCALE)
hh, ww = gray.shape
print(gray.shape)
# get minimum dimensions
hm = min(ht, hh)
wm = min(wd, ww)
print(hm, wm)
# crop img and gray to min dimensions
img = img[0:hm, 0:wm]
gray = gray[0:hm, 0:wm]
# threshold gray as mask
thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)[1]
print(thresh.shape)
# apply mask to color image
result = img.copy()
result[thresh==255] = (0,0,255)
cv2.imshow('image', img)
cv2.imshow('gray', gray)
cv2.imshow('thresh', thresh)
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save results
cv2.imwrite('road_colored_by_mask.png', result)
你的圖片大小不一樣。 要將黑白圖像屏蔽到彩色圖像上,它們需要對齊。 我試圖在左上角簡單地將它們裁剪為相同的最小尺寸,但這並沒有正確對齊它們。
然而,一旦你弄清楚如何對齊它們,這個 Python/OpenCV 代碼會給你一些如何開始的想法。
顏色輸入:
黑白車道圖像:
import cv2
import numpy as np
# read image
img = cv2.imread('road.png')
ht, wd, cc = img.shape
print(img.shape)
# read mask as grayscale
gray = cv2.imread('road_mask.png', cv2.IMREAD_GRAYSCALE)
hh, ww = gray.shape
print(gray.shape)
# get minimum dimensions
hm = min(ht, hh)
wm = min(wd, ww)
print(hm, wm)
# crop img and gray to min dimensions
img = img[0:hm, 0:wm]
gray = gray[0:hm, 0:wm]
# threshold gray as mask
thresh = cv2.threshold(gray,128,255,cv2.THRESH_BINARY)[1]
print(thresh.shape)
# make thresh 3 channels as mask
mask = cv2.merge((thresh, thresh, thresh))
# apply mask to color image
result = cv2.bitwise_and(img, mask)
cv2.imshow('image', img)
cv2.imshow('gray', gray)
cv2.imshow('thresh', thresh)
cv2.imshow('mask', mask)
cv2.imshow('masked image', result)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save results
cv2.imwrite('road_masked_on_black.png', result)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.