pytesseract not recognising image - python

I am building a image de-shredding program, and despite my prepossessing attempts I am still not getting any text output. The images I am putting into it seem as simple as possible. They are binarized and have little to no skew. What am I doing wrong? is there a special neural network library that I am not importing?Image
here is my code
import cv2
import numpy as np
import os
import imutils
from pytesseract import Output
import pytesseract
a1 = 0
a2 = 1
diflist = []
areas = []
images = []
rotated_shreds = []
cropped_shreds = []
idx = 0
scan = cv2.imread('test3.jpeg')
height = scan.shape[0]
width = scan.shape[1]
DrawnContours = np.zeros(shape=[height, width, 3], dtype=np.uint8)
blank_image2 = np.zeros(shape=[height, width, 3], dtype=np.uint8)
#grayscales the image
gray = cv2.cvtColor(scan, cv2.COLOR_BGR2GRAY)
gaus = cv2.GaussianBlur(gray, (3,3),0)
canny_output = cv2.Canny(gaus,50,50)
StripConts, hierarchy= cv2.findContours(canny_output, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
cv2.drawContours(DrawnContours, StripConts, -1, (255,255,255),12)
DrawnContoursgray = cv2.cvtColor(DrawnContours, cv2.COLOR_BGR2GRAY)
DrawConts, hierarchy= cv2.findContours(DrawnContoursgray, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
sorted_contours= sorted(DrawConts, key=cv2.contourArea, reverse= True)
for contour in sorted_contours:
measure = cv2.contourArea(contour)
areas.append(measure)
print(measure)
for area in areas:
try:
dif = areas[a1]-areas[a2]
diflist.append(dif)
a1 += 1
a2 += 1
except:
break
maximum = max(diflist)
del diflist[0]
number = (diflist.index(maximum)+2)
print(number)
for c in sorted_contours:
if idx >= number:
break
else:
x,y,w,h = cv2.boundingRect(c)
new_img=scan[y:y+h,x:x+w]
images.append(new_img)
idx+=1
for image in images:
try:
shred_gaus = cv2.GaussianBlur(image, (3,3),0)
shred_canny_output = cv2.Canny(shred_gaus, 130, 130)
ShredCont, hierarchy = cv2.findContours(shred_canny_output, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
sorted_contours= sorted(ShredCont, key=cv2.contourArea, reverse= True)
cnt = sorted_contours[1]
rect = cv2.minAreaRect(cnt)
angle = rect[2]
if angle < 0:
rotguide = -90 +abs(angle)
print(rotguide)
else:
rotguide = 90 - angle
print(rotguide)
rotated_shred = imutils.rotate_bound(image, rotguide)
rotated_shreds.append(rotated_shred)
except:
counter = 100
for rotated_shred in rotated_shreds:
print("r")
ret, thresh2 = cv2.threshold(rotated_shred, 120, 255, cv2.THRESH_BINARY)
grayfinal = cv2.cvtColor(thresh2, cv2.COLOR_BGR2GRAY)
strait_shred, hierarchy= cv2.findContours(grayfinal, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
sorted_contours= sorted(strait_shred, key=cv2.contourArea, reverse= True)
x,y,w,h = cv2.boundingRect(sorted_contours[0])
new_img=thresh2[y:y+h,x:x+w]
gaus_img = cv2.GaussianBlur(new_img, (3,3),0)
cropped_shreds.append(gaus_img)
cv2.imwrite('rotate.jpeg',cropped_shreds[0])
print(pytesseract.image_to_string(cropped_shreds[1]))

I tried playing with the binarisation values, by blurring it and then binarizing it with a low threshold I fixed it.

Related

My Opencv/Pytesseract script can't detect characters

I have this code:
img = cv2.imread("image.jpg", cv2.IMREAD_UNCHANGED)
img = imutils.resize(img, width=500)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imwrite("output/grayscale conversion.jpg", gray)
gray = cv2.bilateralFilter(gray, 11, 17, 17)
cv2.imwrite("output/bilateralfilter.jpg", gray)
edged = cv2.Canny(gray, 170, 200)
cv2.imwrite("output/cannyedges.jpg", edged)
cnts= cv2.findContours(edged.copy(), cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
cnts=sorted(cnts, key = cv2.contourArea, reverse = True)[:30]
NumberPlateCnt = None
count = 0
for c in cnts:
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
if len(approx) == 4:
NumberPlateCnt = approx
break
# Masking the part other than the number plate
mask = np.zeros(gray.shape,np.uint8)
new_image = cv2.drawContours(mask,[NumberPlateCnt],0,255,-1)
new_image = cv2.bitwise_and(img,img,mask=mask)
cv2.imwrite("output/masked.jpg", new_image)
# Configuration for tesseract
config = ('-l eng --oem 1 --psm 3')
# Run tesseract OCR on image
text = pytesseract.image_to_string(new_image, config=config)
print(text)
cv2.waitKey(0)
return text
when i pass this image as image.jpg it returns the numbers in the plate
But, passing an image like this doesn't
In this case the isolation of the plate doesn't work, it masks almost everything, while
using other images the plate gets isolated but pytesseract still can't convert them to text(see last image)
what am i doing wrong?

Why does the program close when I close the pop-up window in tkinter?

In my program to correct exams by camera (omr) with OpenCV2 and Python 3, it detects the USB camera, but not the program going to the laptop camera (the interior):
import tkinter as tk
import cv2
from PIL import Image, ImageTk
from imutils.perspective import four_point_transform
from imutils import contours
import numpy as np
import argparse
import imutils
import os
import time
import sys
# the time for results name
timestr = time.strftime("%Y%m%d-%H%M%S")
# video frame
width, height = 400, 600
if cv2.VideoCapture(-1) is True:
cap = cv2.VideoCapture(-1)
else:
cap = cv2.VideoCapture(0)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
sucess, frame = cap.read()
def process_bub():
## cam her
cv2.imwrite("images/test10.png", frame)
# load the image, convert it to grayscale, blur it
# slightly, then find edges
cap = cv2.imread("images/test10.png")
gray = cv2.cvtColor(cap, cv2.COLOR_BGR2GRAY)
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 75, 200)
# find contours in the edge map, then initialize
# the contour that corresponds to the document
cnts = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
docCnt = None
# ensure that at least one contour was found
if len(cnts) > 0:
# sort the contours according to their size in
# descending order
cnts = sorted(cnts, key=cv2.contourArea, reverse=True)
# loop over the sorted contours
for c in cnts:
# approximate the contour
peri = cv2.arcLength(c, True)
approx = cv2.approxPolyDP(c, 0.02 * peri, True)
# if our approximated contour has four points,
# then we can assume we have found the paper
if len(approx) == 4:
docCnt = approx
break
# apply a four point perspective transform to both the
# original image and grayscale image to obtain a top-down
# birds eye view of the paper
paper = four_point_transform(cap, docCnt.reshape(4, 2))
warped = four_point_transform(gray, docCnt.reshape(4, 2))
# apply Otsu's thresholding method to binarize the warped
# piece of paper
thresh = cv2.threshold(warped, 0, 255,
cv2.THRESH_BINARY_INV | cv2.THRESH_OTSU)[1]
# find contours in the thresholded image, then initialize
# the list of contours that correspond to questions
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
questionCnts = []
# loop over the contours
for c in cnts:
# compute the bounding box of the contour, then use the
# bounding box to derive the aspect ratio
(x, y, w, h) = cv2.boundingRect(c)
ar = w / float(h)
# in order to label the contour as a question, region
# should be sufficiently wide, sufficiently tall, and
# have an aspect ratio approximately equal to 1
if w >= 20 and h >= 20 and ar >= 0.9 and ar <= 1.1:
questionCnts.append(c)
# sort the question contours top-to-bottom, then initialize
# the total number of correct answers
questionCnts = contours.sort_contours(questionCnts,
method="top-to-bottom")[0]
correct = 0
# each question has 5 possible answers, to loop over the
# question in batches of 5
for (q, i) in enumerate(np.arange(0, len(questionCnts), 4)):
# sort the contours for the current question from
# left to right, then initialize the index of the
# bubbled answer
cnts = contours.sort_contours(questionCnts[i:i + 4])[0]
bubbled = None
# loop over the sorted contours
for (j, c) in enumerate(cnts):
# construct a mask that reveals only the current
# "bubble" for the question
mask = np.zeros(thresh.shape, dtype="uint8")
cv2.drawContours(mask, [c], -1, 255, -1)
# apply the mask to the thresholded image, then
# count the number of non-zero pixels in the
# bubble area
mask = cv2.bitwise_and(thresh, thresh, mask=mask)
total = cv2.countNonZero(mask)
# if the current total has a larger number of total
# non-zero pixels, then we are examining the currently
# bubbled-in answer
if bubbled is None or total > bubbled[0]:
bubbled = (total, j)
# initialize the contour color and the index of the
# *correct* answer
color = (0, 0, 255)
k = ANSWER_KEY[q]
# check to see if the bubbled answer is correct
if k == bubbled[1]:
color = (0, 255, 0)
correct += 1
# draw the outline of the correct answer on the test
cv2.drawContours(paper, [cnts[k]], -1, color, 3)
# grab the test taker
score = (correct / 5.0) * 100
degree = correct
print("[INFO] score: {:.1f}/10".format(degree))
cv2.putText(paper, "{:.1f}/10".format(degree), (10, 30),
cv2.FONT_HERSHEY_SIMPLEX, 0.9, (0, 0, 255), 2)
cv2.imshow("Ohod Resuls", paper)
cv2.imwrite("results/theResult" + timestr + ".png", paper)
cv2.waitKey(0)
# --- functions ---
ANSWER_KEY = {}
def on_button():
for i, var in enumerate(o_vars):
ANSWER_KEY[int(i)] = int(OPTIONS[var.get()])
print()
# --- main ---
OPTIONS = {
'A': '3',
'B': '2',
'C': '1',
'D': '0',
}
root = tk.Tk()
root.title('OhodO')
root.bind('<Escape>', lambda e: root.quit())
lmain = tk.Label(root)
lmain.pack(side ="left")
def show_frame():
_, frame = cap.read()
frame = cv2.flip(frame, 1)
cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)
img = Image.fromarray(cv2image)
imgtk = ImageTk.PhotoImage(image=img)
lmain.imgtk = imgtk
lmain.configure(image=imgtk)
lmain.after(10, show_frame)
show_frame()
def restart_program():
python = sys.executable
os.execl(python, python, *sys.argv)
def dic_clear():
ANSWER_KEY.clear()
# --- OptionMenu ---
tk.Label(root, text='Answer Keys', bg='#aaa').pack(fill='x')
o_vars = []
for i in range(10):
var = tk.StringVar(value='- select -')
o_vars.append(var)
o = tk.OptionMenu(root, var, *OPTIONS)
o.pack()
# --- others ---
b1 = tk.Button(root, text='Ok', command=on_button)
b1.pack(fill='x')
b2 = tk.Button(root, text='Clear', command=dic_clear)
b2.pack(fill='x')
b3 = tk.Button(root, text='Results', command=process_bub)
b3.pack(fill='x')
b4 = tk.Button(root, text='Close', command=root.destroy)
b4.pack(fill='x')
root.mainloop()
The problem is in this code:
b3 = tk.Button(root, text='Results', command=process_bub)
b3.pack(fill='x')
When I click on the "result" button the program work perfectly, that is, it gives me the result for student paper which was put in front of the camera, and saves an image with the result on it. However, when I closed the popup window with the result on it, the program also closes? Why is this?
2- when i clicked (x) in the corner of popup window, the program closed not the popup window ?!.
This program (code) is in (GPL) so you can use it for free.

imread returns None on some images but not others in the same folder

I have been trying to read jpeg images with imread from cv2 package. So far, other than this seemingly random selection of images to read, it has been great.
The problem is that, since I keep all of my images from the same source in the same folder, apparently imread worked on several images but not others for no obvious reason. I have closely inspected and made sure all images are working fine, of the same type, etc. However, as in the screenshots I attach below, only the selected images returned reasonable results whereas all others returned None. The exact code I used here is:
img = cv2.imread(image,1) #most None
Could anyone kindly suggest what possibly went wrong? Many thanks!
My codes as a whole:
images = os.listdir(os.path.join(input_dir, folder))
os.chdir(os.path.join(input_dir, folder))
#index += 1
index_array = []
out = []
# a quick recursion of summing up nested lists
rec = lambda x: sum(map(rec, x)) if isinstance(x, list) else x
minLineLength = 20 ##? how to set these?
maxLineGap = 5 ##? how to set these?
for image in images:
print(image)
if image == ".DS_Store" or (not image.endswith(".jpeg")):
continue
else:
img = cv2.imread(image,1)
#cv2.cv.LoadImage(image,CV_LOAD_IMAGE_COLOR)## #Opening image
if img is None:
print("None")
continue
elif img is not None:
print("Pppppppppaaaaaaaaaaassssssssss!")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY);
edges = cv2.Canny(gray, 50, 120);
nedges = rec(edges.tolist())/255.0;
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength, maxLineGap)
if lines is None:
nlines = 0
elif lines is not None:
nlines = lines.shape[0]
img_blur = cv2.GaussianBlur(gray, (5, 5), 0)
cimg = cv2.cvtColor(img_blur, cv2.COLOR_GRAY2BGR)
circles = cv2.HoughCircles(img_blur, cv2.HOUGH_GRADIENT, 1, 120, param1=100, param2=30, minRadius=0, maxRadius=0)
if circles is None:
ncircles = 0
elif circles is not None:
circles = np.uint16(np.around(circles))
ncircles = circles.shape[1]
gray_blur = cv2.normalize(img_blur, img_blur, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)
ret, thresh = cv2.threshold(gray_blur, 230, 255, cv2.THRESH_BINARY_INV)
square_cnts = []
thresh = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, np.ones((5, 5), np.uint8))
tmpimage, contours, h = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
#print("D")
cnt0 = contours[0]
tmp_h = h[::-1]
appr = []
npoly = []
for index, cnt in enumerate(contours[::-1]):
approx = cv2.approxPolyDP(cnt, 0.1*cv2.arcLength(cnt, True), True)
if approx is None:
continue
elif approx is not None:
appr.append(approx)
npoly.append(len(approx))
new = [nedges, nlines, ncircles, sum(npoly)*1.0/len(npoly)]
out.append(new) #Adding new image to array shape of (x, 3, 100, 100) where x is image number
index_array.append(image)

How can i access the ordering of contours in `opencv`

import cv2
import Image
import numpy as np
#improve image..........................................................
im = cv2.imread('bw_image1.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,11,2)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
i=0
for cnt in contours:
[x,y,w,h] = cv2.boundingRect(cnt)
if h>15:
cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)
im3=im[y:y+h,x:x+w]
cv2.imwrite('objects/pix%i.png'%i,im3)
i+=1
cv2.imshow('norm',im)
cv2.imwrite('objects/shhh.jpg',im)
key = cv2.waitKey(0)
#adding object............
im0 = cv2.imread('objects/pix0.png',0)
im1 = cv2.imread('objects/pix1.png',0)
im2 = cv2.imread('objects/pix2.png',0)
im3 = cv2.imread('objects/pix3.png',0)
im4 = cv2.imread('objects/pix4.png',0)
im5 = cv2.imread('objects/pix5.png',0)
h0, w0 = im0.shape[:2]
h1, w1 = im1.shape[:2]
h2, w2 = im2.shape[:2]
h3, w3 = im3.shape[:2]
h4, w4 = im4.shape[:2]
h5, w5 = im5.shape[:2]
maxh=max(h0,h1,h2,h3,h4,h5)
#add 50 for space between the objects
new = np.zeros((maxh, w0+w1+w2+w3+w4+w5+5),np.uint8)
new=(255-new)
new[maxh-h0:, :w0] = im0
new[maxh-h1:, w0+1:w0+w1+1] = im1
new[maxh-h2:, w0+w1+2:w0+w1+w2+2] = im2
new[maxh-h3:, w0+w1+w2+3:w0+w1+w2+w3+3] = im3
new[maxh-h4:, w0+w1+w2+w3+4:w0+w1+w2+w3+w4+4] = im4
new[maxh-h5:, w0+w1+w2+w3+w4+5:] = im5
gray = cv2.cvtColor(new, cv2.COLOR_GRAY2BGR)
cv2.imshow('norm',gray)
cv2.imwrite('objects/new_image.jpg',gray)
key = cv2.waitKey(0)
# threshold ................................................
im_gray = cv2.imread('objects/new_image.jpg', cv2.CV_LOAD_IMAGE_GRAYSCALE)
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
thresh = 20
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
cv2.imwrite('bw_image1.jpg', im_bw)
im = Image.open('bw_image1.jpg')
im2 = im.resize((300, 175), Image.NEAREST)
im2.save('bw_image1.jpg')
I am using above code to reordering a image
The problem is in final result image is not saving in sequence of main image.
Can anyone tell me how to do it ?
Main image :-
Result image :-
main image and the result image word should look like same. Thank in advance
Opencv find the contours from bottom of the image . so when you try to find the contours of an image like this :
the first contour are for 8 (a bit is lower of 3) then 3 ,7,9,4,e there is not a regular recipe for find the order of contours . so we need to store objects based on theirs x , with this method that from left to right x has been increased , so we can use the below code to store the founded objects after find conturs :
import numpy as np
import cv2
im = cv2.imread('nnn.jpg')
gray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
thresh = cv2.adaptiveThreshold(blur,255,1,1,19,4)
contours,hierarchy = cv2.findContours(thresh,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)
h_list=[]
for cnt in contours:
[x,y,w,h] = cv2.boundingRect(cnt)
if w*h>250:
h_list.append([x,y,w,h])
#print h_list
ziped_list=zip(*h_list)
x_list=list(ziped_list[0])
dic=dict(zip(x_list,h_list))
x_list.sort()
i=0
for x in x_list:
[x,y,w,h]=dic[x]
#cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1)
im3=im[y:y+h,x:x+w]
cv2.imwrite('objects/pix%i.png'%i,im3)
i+=1
cv2.imshow('norm',im)
cv2.imwrite('objects/shhh.jpg',im)
key = cv2.waitKey(0)
Note the line #cv2.rectangle(im,(x,y),(x+w,y+h),(0,0,255),1) has been commented for refusing of extra lines in result image !
then concatenate the saved objects whit this code :
import numpy as np
import cv2
im0 = cv2.imread('objects/pix0.png',0)
im1 = cv2.imread('objects/pix1.png',0)
im2 = cv2.imread('objects/pix2.png',0)
im3 = cv2.imread('objects/pix3.png',0)
im4 = cv2.imread('objects/pix4.png',0)
im5 = cv2.imread('objects/pix5.png',0)
h0, w0 = im0.shape[:2]
h1, w1 = im1.shape[:2]
h2, w2 = im2.shape[:2]
h3, w3 = im3.shape[:2]
h4, w4 = im4.shape[:2]
h5, w5 = im5.shape[:2]
maxh=max(h0,h1,h2,h3,h4,h5)
#add 50 for space between the objects
new = np.zeros((maxh, w0+w1+w2+w3+w4+w5+50),np.uint8)
new=(255-new)
new[maxh-h0:, :w0] = im0
new[maxh-h1:, w0+10:w0+w1+10] = im1
new[maxh-h2:, w0+w1+20:w0+w1+w2+20] = im2
new[maxh-h3:, w0+w1+w2+30:w0+w1+w2+w3+30] = im3
new[maxh-h4:, w0+w1+w2+w3+40:w0+w1+w2+w3+w4+40] = im4
new[maxh-h5:, w0+w1+w2+w3+w4+50:] = im5
gray = cv2.cvtColor(new, cv2.COLOR_GRAY2BGR)
cv2.imshow('norm',gray)
cv2.imwrite('objects/new_image.jpg',gray)
key = cv2.waitKey(0)
result:
import cv2
import numpy as np
im = cv2.imread('0.jpg')
gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray, (5, 5), 0)
thresh = cv2.adaptiveThreshold(blur, 255, 1, 1, 11, 2)
_, contours, hierarchy = cv2.findContours(thresh, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
i = 0
for cnt in contours:
[x, y, w, h] = cv2.boundingRect(cnt)
if h > 15:
cv2.rectangle(im, (x, y), (x + w, y + h), (0, 0, 255), 1)
im3 = im[y:y + h, x:x + w]
cv2.imwrite('ob/pix%i.png' % i, im3)
i += 1
cv2.imshow('norm', im)
key = cv2.waitKey(0)

for i in range(defects.shape): AttributeError: 'NoneType' object has no attribute 'shape'

import cv2
import numpy as np
import sys
import time
import os
cap = cv2.VideoCapture(0)
while( cap.isOpened() ) :
ret,img = cap.read()
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(gray,(5,5),0)
ret,thresh1 = cv2.threshold(blur,70,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
contours, hierarchy = `enter code here`
cv2.findContours(thresh1,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
drawing = np.zeros(img.shape,np.uint8)
max_area=0
enter code here
for i in range(len(contours)):
cnt=contours[i]
area = cv2.contourArea(cnt)
if(area>max_area):
max_area=area
ci=i
cnt=contours[ci]
hull = cv2.convexHull(cnt)
moments = cv2.moments(cnt)
if moments['m00']!=0:
cx = int(moments['m10']/moments['m00']) # cx = M10/M00
cy = int(moments['m01']/moments['m00']) # cy = M01/M00
centr=(cx,cy)
cv2.circle(img,centr,5,[0,0,255],2)
cv2.drawContours(drawing,[cnt],0,(0,255,0),2)
cv2.drawContours(drawing,[hull],0,(0,0,255),2)
cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(cnt,returnPoints = False)
if(1):
defects = cv2.convexityDefects(cnt,hull)
mind=0
maxd=0
i=0
for i in range(defects.shape):
s,e,f,d = defects[i,0]
start = tuple(cnt[s][0])
end = tuple(cnt[e][0])
far = tuple(cnt[f][0])
cv2.line(img,start,end,[0,255,0],2)
cv2.circle(img,far,5,[0,0,255],-1)
print(i)
cv2.imshow('output',drawing)
cv2.imshow('input',img)
k = cv2.waitKey(10)
if k == 27:
break
cnt = cv2.approxPolyDP(cnt,0.01*cv2.arcLength(cnt,True),True)
hull = cv2.convexHull(cnt,returnPoints = False)
defects = cv2.convexityDefects(cnt,hull)
if frame is None:
continue
mind=0
maxd=0
i=0
try to use this if condition.

Categories

Resources