I tried to find contours in my image with cv2.findContours
. So as it uses CV_8UC1 images I tried to convert my array with dtype=np.uint8
, before it was 32 bit. But there I am loosing information. Is there any other way?
The second porblem is the bounding box. The informations are saved in rect
but it is not draw in the picture. Does anyone know why?
Here is my picture/array in 32 bit:
And this is my picture when I added dtype=np.uint8
:
img_hr = np.array(b[1],dtype=np.uint8)
img_hr=img_hr*255
plt.imshow(img_hr)
hierachy, img_threshold = cv2.threshold(img_hr, 100, 255, cv2.THRESH_BINARY)
contours,_ = cv2.findContours(img_threshold, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img_threshold, contours, -1, (0, 255, 0), 2, cv2.LINE_AA)
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img_threshold,[box],0,(0,0,255),2)
cv2.circle(img_threshold,(int(rect[0][0]),int(rect[0][1])),5,(255,0,0),-1)
plt.imshow(img_threshold)
I hope you understand my problem. If not please ask. I appreciate your help. Thanks
I found a solution myself:
First I used the 32-bit image to find the contours with cv2.threshold
in the 32-bit image. After this I convert the 32-bit array to 8-bit np.array(img_threshold_32bit,dtype=np.uint8)
without losing any contours.
So now the input for cv2.drawContours
is an 8-bit array.
But I still have the problem that the bounding-box is not draw in the plot. Any ideas?
Here is the code:
img_hr = np.array(b[1])
hierachy, img_threshold_32bit = cv2.threshold(img_hr, 100, 255, cv2.THRESH_BINARY)
img_8bit = np.array(img_threshold_32bit,dtype=np.uint8)
contours,_ = cv2.findContours(img_8bit, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cv2.drawContours(img_8bit, contours, -1, (0, 255, 0), 2, cv2.LINE_AA)
for cnt in contours:
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
cv2.drawContours(img_8bit,[box],0,(0,0,255),2)
cv2.circle(img_8bit,(int(rect[0][0]),int(rect[0][1])),5,(255,0,0),-1)
plt.imshow(img_8bit)