我使用 OpenCV 和 Python 编写了以下代码:
import cv2
cap = cv2.VideoCapture(1)
cv2.namedWindow('Original')
cv2.namedWindow('Captured')
cv2.namedWindow('Deffects')
while True:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame', frame)
if cv2.waitKey(1) == ord('c'):
cv2.imshow('Captured', gray)
cv2.imwrite('tswira.jpg', frame)
if cv2.waitKey(1) == ord('s'):
img1 = cv2.imread('carte1.jpg', 0)
img2 = cv2.imread('tswira.JPG', 0)
img1 = cv2.resize(img1, (250, 250))
img2 = cv2.resize(img2, (250, 250))
sub = img1 - img2
cv2.imshow('Original', img1)
cv2.imshow('Captured', img2)
cv2.imshow('Deffects', sub)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
Run Code Online (Sandbox Code Playgroud)
这是我得到的输出图像:
然而,我的问题是:如何只裁剪白色区域?
这样做可以做到这一点:
首先,读取图像,转换为灰度,并将那些外部右侧和底部条强制为黑色。
import cv2
import numpy as np
img = cv2.imread('dQF8l.jpg')
img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
img[320:,:]=0
img[:,230:]=0
Run Code Online (Sandbox Code Playgroud)
现在对图像进行阈值处理,找到白点的坐标,并获取白点的最小和最大 x 和 y 坐标。
ret,thresh = cv2.threshold(img,127,255,cv2.THRESH_BINARY)
white_pt_coords=np.argwhere(thresh)
min_y = min(white_pt_coords[:,0])
min_x = min(white_pt_coords[:,1])
max_y = max(white_pt_coords[:,0])
max_x = max(white_pt_coords[:,1])
Run Code Online (Sandbox Code Playgroud)
现在您可以裁剪、书写和显示图像:
crop = img[min_y:max_y,min_x:max_x]
cv2.imshow('orig',img)
cv2.imwrite('crop.jpg',crop)
cv2.waitKey(0)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1632 次 |
| 最近记录: |