[英]Python: How to cut out an area with specific color from image (OpenCV, Numpy)
[英]cut out a specific part of an image with opencv in python
我有一張 IC 芯片的圖像,我想剪掉中心的標記。標記始終位於左下角圓圈上方的特定 position 上。 這個想法是首先找到我已經通過霍夫圓變換完成的圓 position。 現在我想剪掉標記所在的部分。 理想情況下,它應該不是正方形或矩形,而是更像圖像中的東西:
這是我的代碼的一部分:
cimg = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(morph_image, cv2.HOUGH_GRADIENT, 1.3, 20, param1=50, param2=25, minRadius=15,
maxRadius=19)
if circles is not None:
circles = np.uint16(np.around(circles))
for i in circles[0, :]:
# Zeichne äußeren Kreis
cv2.circle(cimg, (i[0], i[1]), i[2], (0, 255, 0), 2)
# Zeichne Kreiszentrum
cv2.circle(cimg, (i[0], i[1]), 2, (0, 0, 255), 3)
# Tupel mit x- und y-Koordinaten des Kreiszentrums
circle_center = (i[0], i[1])
print('Die Koordinaten des Kreiszentrums lauten: ', circle_center)
"""cv2.imshow('Kreis', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()"""
else:
circle_center = None
print('Kein Kreis gefunden')
"""cv2.imshow('Kein Kreis', cimg)
cv2.waitKey(0)
cv2.destroyAllWindows()"""
所以我的cicle center
有我的圓圈的中心 position (例如(124, 370)
)。 如何自動剪切圖像的這一部分? 我可以以某種方式將其裁剪掉嗎? 理想情況下,我想將標記裁剪到另一個圖像中以單獨檢查它,但我猜使用marking_img = img[y:y+h, x:x+w]
的正常裁剪方法行不通。
編輯:這是原始圖像:
output 應該像第一張圖片,如果可能的話,如下所示:
所以最后我想要兩張圖像:一張只有模具沒有標記的圖像和一張只有標記的圖像
這是 Python/OpenCV 中的一種方法。
輸入圖像:
准備好的掩碼圖像:
import cv2
import numpy as np
# read image
img = cv2.imread('die.jpg')
ht, wd, cc = img.shape
# read mask as grayscale
mask = cv2.imread('die_mask.png', cv2.IMREAD_GRAYSCALE)
# threshold mask and invert
mask = cv2.threshold(mask,0,255,cv2.THRESH_BINARY)[1]
mask = 255 - mask
hh, ww = mask.shape
# make mask 3 channel
mask = cv2.merge([mask,mask,mask])
# set circle center
cx = 62
cy = 336
# offsets from circle center to bottom of region
dx = -20
dy = -27
# compute top left corner of mask using size of mask and center and offsets
left = cx + dx
top = cy + dy - hh
# put mask into black background image
mask2 = np.zeros_like(img)
mask2[top:top+hh, left:left+ww] = mask
# apply mask to image
img_masked = cv2.bitwise_and(img, mask2)
# crop region
img_masked_cropped = img_masked[top:top+hh, left:left+ww]
# ALTERNATE just crop input
img_cropped = img[top:top+hh, left:left+ww]
cv2.imshow('image', img)
cv2.imshow('mask', mask)
cv2.imshow('mask2', mask2)
cv2.imshow('masked image', img_masked)
cv2.imshow('masked cropped image', img_masked_cropped)
cv2.imshow('cropped image', img_cropped)
cv2.waitKey(0)
cv2.destroyAllWindows()
# save results
cv2.imwrite('die_mask_inserted.jpg', mask2)
cv2.imwrite('die_masked_image.jpg', img_masked)
cv2.imwrite('die_masked_cropped.jpg', img_masked_cropped)
cv2.imwrite('die_cropped.jpg', img_cropped)
插入黑色圖像的蒙版:
蒙面圖像:
蒙版圖像的裁剪:
(可選)輸入圖像的裁剪:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.