我正在尝试从图像中提取棋盘。它有很多其他不需要的内容,我想删除。所以我创造了一个具有所有斜坡的面具。然后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
掩模和图像的尺寸相同。但我仍然得到这个错误!
答案 0 :(得分:1)
mask
需要由有符号或无符号的8位整数组成。这就是CV_8SC1
和CV_8C1
的含义。
尝试为签名版本创建掩码np.zeros(shape, dtype=np.uint8)
或np.int8
。
同时检查分配给掩码的计算是否属于正确的8位范围:0-255。