gpt4 book ai didi

python - 当我尝试对带有掩码的图像进行 bitwise_and 时,python 出现 OpenCV 错误

转载 作者:太空宇宙 更新时间:2023-11-03 22:51:49 32 4
gpt4 key购买 nike

我正在尝试从图像中提取棋盘。它有很多我想删除的其他不需要的内容。所以我创建了一个包含所有斜坡的面具。然后将其与原始灰度图像进行bitwise_and。我是新手,我发现 OpenCV 非常有趣,但我遇到了这个问题。请帮忙!

import cv2
import numpy as np
from PIL import Image


kernel = np.ones((5,5),np.uint8)
img = cv2.imread('test1.jpg',0)
img = cv2.morphologyEx(img, cv2.MORPH_CLOSE, kernel)

ret,thresh1 = cv2.threshold(img,60,255,cv2.THRESH_BINARY)
edges = cv2.Canny(thresh1,100,200)

cv2.imwrite("canny.jpg", edges)
minL = 10000
maxL = 8
lines = cv2.HoughLinesP(edges,1,np.pi/180, 85)#, minL, maxL)


mask_l = np.zeros(img.shape[:2])
mask_r = np.zeros(img.shape[:2])
mask_t = np.zeros(img.shape[:2])
mask_b = np.zeros(img.shape[:2])


width, height = lines.shape[:2]

im_x, im_y = img.shape


for x1,y1,x2,y2 in lines[0]:
cv2.line(edges,(x1,y1),(x2,y2),(255,255,255),2)
if (x2-x1) == 0:
continue
else:
m = (y2 - y1)/(x2 - x1)
if(m > 0):
for im_count in range(im_x):
yp = round(m * (im_count - x1)) + y1
if yp >= 1 and yp <= im_y:
for temp1 in range(int(im_count),int(im_x)):
mask_r[int(yp)][int(temp1)] = 1
for temp2 in range(int(im_count)):
mask_l[int(yp)][int(temp2)] = 1
else:
for im_count in range(im_x):
yp = round(m * (im_count - x1)) + y1
if yp >= 1 and yp <= im_y:
for temp1 in range(int(yp), int(im_y)):
mask_b[int(im_count)][int(temp1)] = 1
for temp2 in range(int(yp)):
mask_t[int(im_count)][int(temp2)] = 1

cv2.imwrite('new.jpg', edges)


temp_mask1 = cv2.bitwise_and(mask_l, mask_r, mask=None)
temp_mask2 = cv2.bitwise_and(mask_t, mask_b, mask=None)
final_mask = cv2.bitwise_and(temp_mask1, temp_mask2)




final_mask = cv2.morphologyEx((final_mask * 1.0).astype(np.float32), cv2.MORPH_CLOSE, kernel=None)

cv2.imshow('final',final_mask)
cv2.waitKey(0)


cv2.destroyAllWindows()

x,y = img.shape
print x
print y
ret, orig_mask = cv2.threshold(final_mask, 10, 255, cv2.THRESH_BINARY)
a,b = final_mask.shape
print a
print b


imeg = cv2.imread('test1.jpg',cv2.CV_LOAD_IMAGE_GRAYSCALE)

ret, orig_mask1 = cv2.threshold(imeg, 10, 255, cv2.THRESH_BINARY)
(thresh, im_bw) = cv2.threshold(imeg, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
images1 = cv2.bitwise_and(img,img, mask=orig_mask)
cv2.imwrite("123.jpg",images1)

这是我遇到的错误:

OpenCV Error: Assertion failed ((mask.type() == CV_8UC1 || mask.type() == CV_8SC1)) in binary_op, file /build/buildd/opencv-2.3.1/modules/core/src/arithm.cpp, line 1033

蒙版和图像的尺寸相同。但我仍然收到此错误!

最佳答案

mask 需要由有符号或无符号的 8 位整数组成。这就是 CV_8SC1CV_8C1 的意思。

尝试将掩码创建为 np.zeros(shape, dtype=np.uint8)np.int8 签名版本。

还要检查分配给掩码的计算是否落入正确的 8 位范围:0-255。

关于python - 当我尝试对带有掩码的图像进行 bitwise_and 时,python 出现 OpenCV 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37011321/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com