Reputation: 124
I have problems using OpenCV in python, as I'm quite unfamiliar with it. I'm trying to use a two-dimensional array with OpenCV to find lines in it. The data I have never has been an image file and I don't want to create an image just to encode it to an array again. Basically I search for an array alternative for img = cv2.imread(file_path)
. This might be obvious how to do, but I couldn't find anything fitting for my purpose.
Minimalistic example for what I'm planning to do:
import numpy as np
import cv2
my_list = np.array([[1,0,1],[2,0,1],[2,0,2]])
img = cv2.imread(my_list) # this is what I need to replace
edges = cv2.Canny(gray,70,110,apertureSize = 3)
#and so on
lines = cv2.HoughLines(edges,1,np.pi/180,150)
Long story short: how to use an array with OpenCV.
Upvotes: 0
Views: 6184
Reputation: 899
I think this is what you are looking for. you need to add one more dimension to your list of points using np.expand_dims
import numpy as np
import cv2
my_list = np.array([[1, 0, 1], [2, 0, 1], [2, 0, 2]], dtype=np.uint8)
img = np.expand_dims(my_list, axis=0)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 70, 110, apertureSize=3)
# and so on
lines = cv2.HoughLines(edges, 1, np.pi / 180, 150)
EDIT:
As you have clarified that your input list's values are from the gray colour space.
you can simply change array datatype to np.uint8
and it will work.
import numpy as np
import cv2
my_list = np.array([[1, 0, 1], [2, 0, 1], [2, 0, 2]], dtype=np.uint8)
edges = cv2.Canny(my_list, 70, 110, apertureSize=3)
# and so on
lines = cv2.HoughLines(edges, 1, np.pi / 180, 150)
Upvotes: 1
Reputation: 23101
Just visualizing with a slightly larger 2D array and detecting the diagonal line present in the array with the following code:
my_list = np.eye(100) #np.array([[0,1,0,1],[0,2,0,1],[0,2,0,2]])
gray = (255*my_list/np.max(my_list)).astype('uint8')
edges = cv2.Canny(gray,70,110,apertureSize = 3)
lines = cv2.HoughLines(edges,1,np.pi/180,50)
lines
# array([[[-1. , 2.3561945]],
# [[ 1. , 2.3561945]]], dtype=float32)
# original image
plt.imshow(gray, 'gray')
plt.show()
# canny edges detected
plt.imshow(edges)
plt.show()
# lines detected with Hough transform
im = cv2.cvtColor(gray, cv2.COLOR_GRAY2BGR)
if lines is not None:
for i in range(len(lines)):
rho = lines[i][0][0]
theta = lines[i][0][3]
a = np.cos(theta)
b = np.sin(theta)
x0 = a * rho
y0 = b * rho
pt1 = (int(x0 + 1000*(-b)), int(y0 + 1000*(a)))
pt2 = (int(x0 - 1000*(-b)), int(y0 - 1000*(a)))
print(pt1, pt2)
cv2.line(im, pt1, pt2, (0,0,255), 2, cv2.LINE_AA)
plt.imshow(im)
plt.show()
Upvotes: 1