簡體   English   中英

OpenCV:僅返回圖像的選定區域並將其余部分返回為黑色

[英]OpenCV: return only selected area of an image and return the rest as black

我正在嘗試選擇圖像的某個區域,它已經成功了。 但是,還有一個問題,所選區域與源圖像不在同一位置。 這是關於它的可視化:

左圖是我生成的區域。 但它不在我想要的正確圖像中的正確位置。

這是我已經嘗試過的簡單代碼:

import cv2
import NumPy as np

pic= cv2.imread('set.jpeg')
pic = cv2.resize(pic, dsize=(500, 400), interpolation=cv2.INTER_CUBIC)
gray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),5)
_,thres = cv2.threshold(blur, 100,250, cv2.THRESH_TOZERO)
res = cv2.Canny(thres, 100, 200, L2gradient=True)

circles = cv2.HoughCircles(res,cv2.HOUGH_GRADIENT,1,20,param1=200,param2=15,minRadius=80,maxRadius=100)

crops = []
for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(pic,(int(i[0]),int(i[1])),int(i[2]),(255,255,255),2)
    i = i.astype(int)
    crop = res[i[1]-i[2]:i[1]+i[2], i[0]-i[2]:i[0]+i[2]]
    crop = np.pad(crop,[(101, ), (151, )], mode='constant')
    crops.append(crop)

result = np.concatenate((crops[0],res),axis=1)
cv2.imshow('Hole',result)

cv2.waitKey(0)
cv2.destroyAllWindows()

我想要像正確的圖像一樣的結果(只生成藍色框圖像)並將其余的返回為黑色(如左圖)。

有什么辦法可以在我想要的正確位置獲得結果嗎? (如右圖)謝謝!!

該問題已通過創建蒙版並通過以下代碼行組合前景和背景來解決:

import cv2
import numpy as np

pic= cv2.imread('Assets/set.jpeg')
pic = cv2.resize(pic, dsize=(500, 400), interpolation=cv2.INTER_CUBIC)
gray=cv2.cvtColor(pic,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),5)
_,thres = cv2.threshold(blur, 100,250, cv2.THRESH_TOZERO)
res = cv2.Canny(thres, 100, 250, L2gradient=True)

circles = cv2.HoughCircles(res,cv2.HOUGH_GRADIENT,1,20,param1=200,param2=15,minRadius=80,maxRadius=100)
circles = np.uint16(np.around(circles))

mask = np.full((res.shape[0], res.shape[1]), 1, dtype=np.uint8)  # mask is only 
clone = pic.copy()
for i in circles[0, :]:
    cv2.circle(mask, (i[0], i[1]), i[2], (255, 255, 255), -1)
    cv2.circle(clone, (i[0], i[1]), i[2], (255, 255, 255), 1)

# get first masked value (foreground)
fg = cv2.bitwise_or(res, res, mask=mask)

# get second masked value (background) mask must be inverted
mask = cv2.bitwise_not(mask)
background = np.full(res.shape, 255, dtype=np.uint8)
bk = cv2.bitwise_or(background, background, mask=mask)

# combine foreground+background
final = cv2.bitwise_or(fg, bk)

result = np.concatenate((res,final),axis=1)
cv2.imshow('Hole',result)
cv2.waitKey(0)
cv2.destroyAllWindows()

沒什么可問的了,我會結束這個問題。 謝謝!!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM