AttributeError: module 'cv2.cv2' has no attribute 'rectange' - python-3.x

I am using the following code on python 3.7
import cv2
import numpy as np
face_cascade = cv2.CascadeClassifier('D:\\ET\\haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('D:\\ET\\haarcascade_eye.xml')
cap = cv2.VideoCapture(0)
while True:
ret, img = cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x,y,w,h) in faces:
cv2.rectange(img,(x,y),(x+w,y+h),(255,0,0),2)
roi_gray = gray[y:y+h, x:x+w]
roi_color = img[y:y+h, x:x+w]
eyes = eye_cascade.detectMultiScale(roi_gray)
for (ex,ey,ew,eh) in eyes:
cv2.rectangle(roi_color,(ex,ey), (ex+ew,ey+eh),(0,255,0),2)
cv2.imshow('img',img)
k = cv2.waitKey(30) & 0xFF
if k == 27:
break
cap.release()
cv2.destroyAllWindows()
the following is installed:
opencv-contrib-python-3.4.4.19

The error is telling you that cv2 doesn't have anything called rectange, but it does have something called rectangle. You misspelled it:
cv2.rectange(img,(x,y),(x+w,y+h),(255,0,0),2)

Related

why is this attribute error showing up and what is the solution to it

i m running a code and its giving this attribute error pls help
the error that is shows while running the code
the code i am using:_
import cv2
from deepface import DeepFace
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + "haarcascade_frontalface_default.xml")
cap = cv2.VideoCapture(0)
if not cap.isOpened():
cap = cv2.VideoCapture(0)
if not cap.isOpened():
raise IOError("Cannot open webcam")
while True:
ret, frame = cap.read()
result = DeepFace.analyze(frame, actions = ["emotion"])
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray,1.1,4)
for(x,y,w,h) in faces:
cv2.rectangle(frame,(x,y),(x+w,y+h),(0,255,0),2)
font = cv2.FONT_HERSHEY_SIMPLEX
cv2.putText('video',frame)
if cv2.waitKey(2) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

OpenCV do not want to stop video recording with cv2.COLOR_BGR2GRAY

when i run this code:
from cv2 import *
image = cv2.VideoCapture(0, cv2.CAP_DSHOW)
fourcc_cod = cv2.VideoWriter_fourcc(*"XVID")
name = input()
video = cv2.VideoWriter(f"{name}.AVI",fourcc_cod,60,(640,480))
while (True):
check,frame = image.read()
frame1 = cvtColor(frame, cv2.COLOR_BGR2GRAY)
video.write(frame1)
cv2.imshow('myimage',frame1)
if waitKey(1) ord('q'):
cv2.destroyAllWindows()
video.release()
image.release()
it does not stop recording the video Even if I press "q"
Try this snippet.
import cv2
cap = cv2.VideoCapture(0)
name = input()
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter(f'{name}.avi', fourcc, 20.0, (640, 480))
while True:
ret, frame = cap.read()
frame = cv2.flip(frame, 0)
# uncomment belove line for grayscale
# frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# write the flipped frame
out.write(frame)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release everything if job is finished
cap.release()
out.release() # video file writer
cv2.destroyAllWindows()

issues with CNN to make predictions in video frames

import cv2
import numpy as np
import tensorflow as tf
model = tf.keras.models.load_model("oneptwoside.model")
CATEGORIES = ["front", "back"]
cap = cv2.VideoCapture(0)
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
while ret:
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('frame',gray)
IMG_SIZE = 200
img_array = cv2.imread(frame, cv2.IMREAD_GRAYSCALE)
new_array = cv2.resize(img_array, (IMG_SIZE, IMG_SIZE))
prediction = model.predict([img_array])
print(prediction)
print(CATEGORIES[int(prediction[0][0])])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
I cant make predictions with my webcam. I try the same code in image it's working fine with a little bit of tweak. However in video is always not reading the frame or some resizing issue
if cap.isOpened():
ret, frame = cap.read()
else:
ret = False
while ret:
curr_time = time.time()
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
curTime = time.time()
sec = curTime - prevTime
prevTime = curTime
fps = 1/(sec)
str = "FPS : %0.1f" % fps
cv2.putText(frame, str, (0, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 150, 0))
cv2.imshow('frame',gray)
cv2.imshow('color', frame)
if curr_time - last_recorded_time >= 0.0001:
last_recorded_time = curr_time
IMG_SIZE = 200
#img_array = cv2.imread('frame', cv2.IMREAD_GRAYSCALE)
frame = cv2.resize(frame, None, fx=0.5, fy=0.5)
frame = cv2.resize(frame, (IMG_SIZE, IMG_SIZE))
#frame = frame[np.newaxis, ...]
frame = frame.reshape((-1, 200, 200, 1))
cv2.rectangle(frame,(200,0),(150,128),(0,255,0),3)
prediction = model.predict([frame])
#prediction = model.predict([frame])
print(prediction)
print(CATEGORIES[int(prediction[0][0])])
if cv2.waitKey(1) & 0xFF == ord('q'):
break
here is a solution not ideal but it's working

How to draw arabic text on the image using `cv2.putText`correctly? (Python+OpenCV)

I use python cv2(window10, python3.6) to write text in the image, when the text is English it works, but when I use Arabic text it writes messy code in the image.
Below is my code:
import cv2
import numpy as np
blank_image = np.zeros((100,300,3), np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
org = (10, 50)
fontScale = .5
color = (255, 0, 0)
thickness = 1
blank_image = cv2.putText(blank_image, "اللغة العربية", org, font,
fontScale, color, thickness, cv2.LINE_AA)
window_name = 'Image'
cv2.imshow(window_name, blank_image)
cv2.waitKey(0)
cv2.destroyAllWindows()
the problem here
blank_image = cv2.putText(blank_image, "اللغة العربية", org, font,
fontScale, color, thickness, cv2.LINE_AA)
fontpath = "arial.ttf" # <== download font
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),'عربي', font = font)
img = np.array(img_pil)
cv2.imshow(window_name, img)
import cv2
import arabic_reshaper
from bidi.algorithm import get_display
import numpy as np
from PIL import ImageFont, ImageDraw, Image
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
text = "ذهب الطالب الى المدرسة"
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
fontpath = "arial.ttf" # <== https://www.freefontspro.com/14454/arial.ttf
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(frame)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),bidi_text, font = font)
img = np.array(img_pil)
cv2.imshow('window_name', img)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
#before opening the programme
#first download arabic_reshaper lib write in Anaconda prompt
#"pip install arabic_reshaper"
#and download bidi lib write in Anaconda prompt
#"pip install python-bidi"
import arabic_reshaper
from bidi.algorithm import get_display
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import cv2
img =cv2.imread("sun.jpg")
fontpath = "arial.ttf" # <== download font
font = ImageFont.truetype(fontpath, 32)
img_pil = Image.fromarray(img)
draw = ImageDraw.Draw(img_pil)
text="اللغة العربية"
reshaped_text = arabic_reshaper.reshape(text)
bidi_text = get_display(reshaped_text)
draw = ImageDraw.Draw(img_pil)
draw.text((50, 80),bidi_text, font = font)
img = np.array(img_pil)
cv2.imshow("image with arabic", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Threading or multiprocessing implementation into face detection/ Tkinter app

So basically I have an app that has a splash screen Tkinter frame.
I need this frame to close when openCV detects a face, after which openCV opens a window that shows the camera feed and starts tracking smiles. The other classes initialized in the code below are for updating a database and playing a DTMF tone when a smile is recognized, my main issue is that the mainloop from the Tkinter frame won't allow any other processes to continue.
I also need the Tkinter frame to close when a face is detected. Right now I tried setting it up with a separate face detection loop dedicated just to closing the frame (the frames class has a facefound() function which just calls a self.destroy()).
I need to multiprocess the frame's mainloop so that the face detector can actually check whether or not a face is in view.
Current code:
import numpy as np
import sys
from imutils.video import VideoStream
import datetime
import argparse
import imutils
import time
import cv2
from chocolate_returner import Choco_returner
from given_resetter import Given_resetter
from tone_player import Tone_player
from play_flagger import Play_flagger
from Welcome_frame import Intro
import time
ap = argparse.ArgumentParser()
ap.add_argument("-p", "--picamera", type=int, default=-1,
help="whether or not the Raspberry Pi camera should be used")
args = vars(ap.parse_args())
faceCascade = cv2.CascadeClassifier('faces.xml')
smileCascade = cv2.CascadeClassifier('smiles.xml')
cap = VideoStream(usePiCamera=args["picamera"] > 0).start()
time.sleep(2.0)
while True:
framex = cap.read() # Capture frame-by-frame
frame = imutils.resize(framex, width=400)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=0
)
# ---- Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
print "found ", len(faces), "faces"
roi_gray = gray[y:y + h, x:x + w]
roi_color = frame[y:y + h, x:x + w]
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
if (len(faces) > 0):
check = True
it.facefound()
break
while True:
framex = cap.read() # Capture frame-by-frame
frame = imutils.resize(framex, width=400)
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor= 1.1,
minNeighbors=5,
minSize=(30, 30),
flags=0
)
# ---- Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
print "found ", len(faces), "faces"
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
smile = smileCascade.detectMultiScale(
roi_gray,
scaleFactor= 1.7,
minNeighbors=5,
minSize=(5, 5),
flags=0
)
time.sleep(2.0)
# Set region of interest for smiles
for (x, y, w, h) in smile:
print "Found", len(smile), "smiles!"
cv2.rectangle(roi_color, (x, y), (x+w, y+h), (255, 0, 0), 1)
img = framex
cv2.imwrite("test.jpg", img)
cr = Choco_returner()
gr = Given_resetter()
tp = Tone_player()
pf = Play_flagger()
if (len(smile) > 0):
return1 = cr.returner()
tp.play(str(return1[1]), str(return1[2]))
pf.flag(return1[0])
#print "!!!!!!!!!!!!!!!!!"
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()

Resources