What's new

Help Mga master patulong kahit simple code lang para sa raspberry pi

BrigthWin

Forum Veteran
Elite
Joined
Jul 21, 2020
Posts
1,639
Reaction
1,768
Points
650
May project po kaming automatic trashbin segregator tapos meron napo akong na train na model which is biodegradable and non biodegradable gamit ang tensorflow . So bale may nahanap akong code kaya lang yung na train nila na model yung lang gumagawa sa code na yun. Pano kaya mapagana yung na sarili kong train na model tapos at the same time nag wowork din ang servo motor which responsible sa pag segregate.

Ito po ang code:
import cv2
ima numpy as np
from gpiozero import AngularServo,LED
import time
from tflite_support.task import core
from tflite_support.task import processor
from tflite_support.task import vision

base_options = core.BaseOptions(file_name='model.tflite', use_coral=False, num_threads=4)
classification_options = processor.ClassificationOptions(max_results=3, score_threshold=0.0)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)
freeLED = LED(16)
busyLED = LED(26)

camera=cv2.VideoCapture(0, cv2.CAP_V4L)
width = 512
height = 512
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

first_time=0
frame_buffer=0
counter=0

time.sleep(1)

def imageSubtract(img):
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
return hsv

s=AngularServo(18, min_angle=-90, max_angle=90)
def setServoAngle(angle):
s.angle=angle

aa=0

from datetime import datetime

while True:
_, frame = camera.read()
if first_time==0:
if frame_buffer<30:
frame_buffer+=1
continue
refImg=frame
refImg=refImg[40:490,25:]
refThresh=imageSubtract(refImg)
first_time=1
frame_buffer=0
busyLED.off()
freeLED.on()
print("Started camera read")
frame_buffer+=1
image = frame
image=image[40:490,25:]
#cv2.imshow('Camera Feed',image)
if counter==1:
if aa<120:
aa+=1
continue
cdatetimeunf=datetime.now()
cdatetime=cdatetimeunf.strftime("%d-%B-%Y %H-%M-%S")
folder="/home/pi/Trash-Segregator/static/images/"+cdatetimeunf.strftime("%Y")+"/"+cdatetimeunf.strftime("%B")
file_name=cdatetime+".jpeg"
file_path=os.path.join(folder,file_name)
if not os.path.exists(folder):
os.system('mkdir -p '+folder)
cv2.imwrite(file_path,image)
tensor_image=vision.TensorImage.create_from_file(file_path)
categories = classifier.classify(tensor_image)
bio=False
for idx, category in enumerate(categories.classifications[0].categories):
category_name = category.category_name
score = round(category.score, 2)
if category_name=='bio':
bioScore=score
if category_name=='non-bio':
nonBioScore=score
if bioScore>nonBioScore:
bio=True
elif bioScore<nonBioScore:
bio=False
print("b,nb",bioScore,",",nonBioScore)
if bio:
confidence=str(bioScore*100)
print("Waste is Biodegradable")
setServoAngle(-90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
elif not bio:
confidence=str(nonBioScore*100)
print("Waste is Non-biodegradable")
setServoAngle(90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Non-Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
t_end=0
first_time=0
frame_buffer=0
counter=0
print("Waste segregated !")
time.sleep(1)
freeLED.on()


newThresh=imageSubtract(image)
diff=cv2.absdiff(refThresh,newThresh)
diff=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
kernel=np.ones((5,5),np.uint8)
diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)
diff=cv2.erode(diff,kernel,iterations = 2)
diff=cv2.dilate(diff,kernel,iterations = 3)

_, thresholded = cv2.threshold(diff, 0 , 255, cv2.THRESH_BINARY +cv2.THRESH_OTSU)
contours, _= cv2.findContours(thresholded,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
try:
if counter==0:
c=max(contours,key=cv2.contourArea)
mask = np.zeros(newThresh.shape[:2],np.uint8)
new_image = cv2.drawContours(mask,[c],0,255,-1,)
if cv2.contourArea(c)>1000 and len(contours)<=4:
if counter==0:
busyLED.on()
freeLED.off()
print("Possible object detcted")
counter=1
aa=0
print("set counter to 1")
continue
except Exception as e:
print(e)
pass
 
Magandang araw! Para mapaikot mo ang code gamit ang sarili mong train na model, dapat mong baguhin ang file name sa base_options ng core. Ito ay nagsasabi kung alin ang file name ng model na gagamitin ng program. Kung mayroon ka nang train na model, dapat mong ilagay ang pangalan ng iyong train model file sa file name ng base_options. Halimbawa:

Code:
base_options = core.BaseOptions(file_name='my_trained_model.tflite', use_coral=False, num_threads=4)

Dapat din siguraduhin mong naa-update ang classification_options, ayon sa mga kategorya ng iyong train na model. Kung ang iyong train na model ay may dalawang uri ng basura, maaari mong gamitin ito:

Code:
classification_options = processor.ClassificationOptions(max_results=2, score_threshold=0.5)

Umiiral din sa code ang servo motor na ginagamit upang mag-segregate ng mga basura. Pwede mo itong i-modify upang gumana sa iyong train na model. Siguraduhin na ang servo motor ay naka-connect sa tamang GPIO pin ng Raspberry Pi.

Code:
s=AngularServo(18, min_angle=-90, max_angle=90)
def setServoAngle(angle):
    s.angle=angle

Sa code na ito, ang servo motor ay nakakabit sa pin 18 ng Raspberry Pi. Ang angle ay maaaring mag-iba ayon sa kategorya ng basura. Halimbawa, ang angle na -90 ay nagpapakita ng biodegradable na basura, samantalang ang angle na 90 ay nagpapakita ng non-biodegradable na basura. Ito ay maaaring baguhin sa pamamagitan ng pag-uugnay ng angle sa train na model.

Ipagpatuloy ang pagbabago ng code at subukang i-implement ang iyong train na model. Kung mayroong iba pang mga katanungan, huwag mag-atubiling magtanong.
 
Magandang araw! Para mapaikot mo ang code gamit ang sarili mong train na model, dapat mong baguhin ang file name sa base_options ng core. Ito ay nagsasabi kung alin ang file name ng model na gagamitin ng program. Kung mayroon ka nang train na model, dapat mong ilagay ang pangalan ng iyong train model file sa file name ng base_options. Halimbawa:

Code:
base_options = core.BaseOptions(file_name='my_trained_model.tflite', use_coral=False, num_threads=4)

Dapat din siguraduhin mong naa-update ang classification_options, ayon sa mga kategorya ng iyong train na model. Kung ang iyong train na model ay may dalawang uri ng basura, maaari mong gamitin ito:

Code:
classification_options = processor.ClassificationOptions(max_results=2, score_threshold=0.5)

Umiiral din sa code ang servo motor na ginagamit upang mag-segregate ng mga basura. Pwede mo itong i-modify upang gumana sa iyong train na model. Siguraduhin na ang servo motor ay naka-connect sa tamang GPIO pin ng Raspberry Pi.

Code:
s=AngularServo(18, min_angle=-90, max_angle=90)
def setServoAngle(angle):
    s.angle=angle

Sa code na ito, ang servo motor ay nakakabit sa pin 18 ng Raspberry Pi. Ang angle ay maaaring mag-iba ayon sa kategorya ng basura. Halimbawa, ang angle na -90 ay nagpapakita ng biodegradable na basura, samantalang ang angle na 90 ay nagpapakita ng non-biodegradable na basura. Ito ay maaaring baguhin sa pamamagitan ng pag-uugnay ng angle sa train na model.

Ipagpatuloy ang pagbabago ng code at subukang i-implement ang iyong train na model. Kung mayroong iba pang mga katanungan, huwag mag-atubiling magtanong.
It didn't work help

IMG_20230621_110619_640.jpg
 

Attachments

Sorry to hear that it didn't work. Can you please provide more information on what didn't work and what error messages did you get? This will help me better understand the issue and provide you with the appropriate solution. Thank you.

Ito pong code yung ginamit ko at pinalitan ko ang file name yung nilagay ko yung na train ko na model dahil yun po ang suggestion mo at yung max_results ginawa kong 2 at score_treshold din ginawa kong 0.5
Ito po yung code;
import cv2
ima numpy as np
from gpiozero import AngularServo,LED
import time
from tflite_support.task import core
from tflite_support.task import processor
from tflite_support.task import vision

base_options = core.BaseOptions(file_name='model1.1.tflite', use_coral=False, num_threads=4)
classification_options = processor.ClassificationOptions(max_results=2, score_threshold=0.5)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)
freeLED = LED(16)
busyLED = LED(26)

camera=cv2.VideoCapture(0, cv2.CAP_V4L)
width = 512
height = 512
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

first_time=0
frame_buffer=0
counter=0

time.sleep(1)

def imageSubtract(img):
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
return hsv

s=AngularServo(18, min_angle=-90, max_angle=90)
def setServoAngle(angle):
s.angle=angle

aa=0

from datetime import datetime

while True:
_, frame = camera.read()
if first_time==0:
if frame_buffer<30:
frame_buffer+=1
continue
refImg=frame
refImg=refImg[40:490,25:]
refThresh=imageSubtract(refImg)
first_time=1
frame_buffer=0
busyLED.off()
freeLED.on()
print("Started camera read")
frame_buffer+=1
image = frame
image=image[40:490,25:]
#cv2.imshow('Camera Feed',image)
if counter==1:
if aa<120:
aa+=1
continue
cdatetimeunf=datetime.now()
cdatetime=cdatetimeunf.strftime("%d-%B-%Y %H-%M-%S")
folder="/home/pi/Trash-Segregator/static/images/"+cdatetimeunf.strftime("%Y")+"/"+cdatetimeunf.strftime("%B")
file_name=cdatetime+".jpeg"
file_path=os.path.join(folder,file_name)
if not os.path.exists(folder):
os.system('mkdir -p '+folder)
cv2.imwrite(file_path,image)
tensor_image=vision.TensorImage.create_from_file(file_path)
categories = classifier.classify(tensor_image)
bio=False
for idx, category in enumerate(categories.classifications[0].categories):
category_name = category.category_name
score = round(category.score, 2)
if category_name=='bio':
bioScore=score
if category_name=='non-bio':
nonBioScore=score
if bioScore>nonBioScore:
bio=True
elif bioScore<nonBioScore:
bio=False
print("b,nb",bioScore,",",nonBioScore)
if bio:
confidence=str(bioScore*100)
print("Waste is Biodegradable")
setServoAngle(-90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
elif not bio:
confidence=str(nonBioScore*100)
print("Waste is Non-biodegradable")
setServoAngle(90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Non-Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
t_end=0
first_time=0
frame_buffer=0
counter=0
print("Waste segregated !")
time.sleep(1)
freeLED.on()


newThresh=imageSubtract(image)
diff=cv2.absdiff(refThresh,newThresh)
diff=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
kernel=np.ones((5,5),np.uint8)
diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)
diff=cv2.erode(diff,kernel,iterations = 2)
diff=cv2.dilate(diff,kernel,iterations = 3)

_, thresholded = cv2.threshold(diff, 0 , 255, cv2.THRESH_BINARY +cv2.THRESH_OTSU)
contours, _= cv2.findContours(thresholded,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
try:
if counter==0:
c=max(contours,key=cv2.contourArea)
mask = np.zeros(newThresh.shape[:2],np.uint8)
new_image = cv2.drawContours(mask,[c],0,255,-1,)
if cv2.contourArea(c)>1000 and len(contours)<=4:
if counter==0:
busyLED.on()
freeLED.off()
print("Possible object detcted")
counter=1
aa=0
print("set counter to 1")
continue
except Exception as e:
print(e)

Nag error siya ito po nakalagay sa shell;


Traceback (most recent call last):
File "/home/pi/Trash-Segregator/rongie.py", line 13, in <module>
classifier = vision.ImageClassifier.create_from_options(options)
File "/home/pi/.local/lib/python3.9/site-packages/tensorflow_lite_support/python/task/vision/image_classifier.py", line 88, in create_from_options
classifier = CppImageClassifier.create_from_options(
RuntimeError: Input tensor has type kTfliteFloat32: it requires specifying NormalizationOptions metadata to preprocess input images.
 





Ito pong code yung ginamit ko at pinalitan ko ang file name yung nilagay ko yung na train ko na model dahil yun po ang suggestion mo at yung max_results ginawa kong 2 at score_treshold din ginawa kong 0.5
Ito po yung code;
import cv2
ima numpy as np
from gpiozero import AngularServo,LED
import time
from tflite_support.task import core
from tflite_support.task import processor
from tflite_support.task import vision

base_options = core.BaseOptions(file_name='model1.1.tflite', use_coral=False, num_threads=4)
classification_options = processor.ClassificationOptions(max_results=2, score_threshold=0.5)
options = vision.ImageClassifierOptions(base_options=base_options, classification_options=classification_options)
classifier = vision.ImageClassifier.create_from_options(options)
freeLED = LED(16)
busyLED = LED(26)

camera=cv2.VideoCapture(0, cv2.CAP_V4L)
width = 512
height = 512
camera.set(cv2.CAP_PROP_FRAME_WIDTH, width)
camera.set(cv2.CAP_PROP_FRAME_HEIGHT, height)

first_time=0
frame_buffer=0
counter=0

time.sleep(1)

def imageSubtract(img):
hsv=cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
return hsv

s=AngularServo(18, min_angle=-90, max_angle=90)
def setServoAngle(angle):
s.angle=angle

aa=0

from datetime import datetime

while True:
_, frame = camera.read()
if first_time==0:
if frame_buffer<30:
frame_buffer+=1
continue
refImg=frame
refImg=refImg[40:490,25:]
refThresh=imageSubtract(refImg)
first_time=1
frame_buffer=0
busyLED.off()
freeLED.on()
print("Started camera read")
frame_buffer+=1
image = frame
image=image[40:490,25:]
#cv2.imshow('Camera Feed',image)
if counter==1:
if aa<120:
aa+=1
continue
cdatetimeunf=datetime.now()
cdatetime=cdatetimeunf.strftime("%d-%B-%Y %H-%M-%S")
folder="/home/pi/Trash-Segregator/static/images/"+cdatetimeunf.strftime("%Y")+"/"+cdatetimeunf.strftime("%B")
file_name=cdatetime+".jpeg"
file_path=os.path.join(folder,file_name)
if not os.path.exists(folder):
os.system('mkdir -p '+folder)
cv2.imwrite(file_path,image)
tensor_image=vision.TensorImage.create_from_file(file_path)
categories = classifier.classify(tensor_image)
bio=False
for idx, category in enumerate(categories.classifications[0].categories):
category_name = category.category_name
score = round(category.score, 2)
if category_name=='bio':
bioScore=score
if category_name=='non-bio':
nonBioScore=score
if bioScore>nonBioScore:
bio=True
elif bioScore<nonBioScore:
bio=False
print("b,nb",bioScore,",",nonBioScore)
if bio:
confidence=str(bioScore*100)
print("Waste is Biodegradable")
setServoAngle(-90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
elif not bio:
confidence=str(nonBioScore*100)
print("Waste is Non-biodegradable")
setServoAngle(90)
time.sleep(5)
setServoAngle(0)
new_name=file_name.replace(".jpeg","_Non-Biodegradable.jpeg")
new_name=confidence+"_"+new_name
os.rename(file_path,os.path.join(folder,new_name))
t_end=0
first_time=0
frame_buffer=0
counter=0
print("Waste segregated !")
time.sleep(1)
freeLED.on()


newThresh=imageSubtract(image)
diff=cv2.absdiff(refThresh,newThresh)
diff=cv2.cvtColor(diff,cv2.COLOR_BGR2GRAY)
kernel=np.ones((5,5),np.uint8)
diff = cv2.morphologyEx(diff, cv2.MORPH_OPEN, kernel)
diff=cv2.erode(diff,kernel,iterations = 2)
diff=cv2.dilate(diff,kernel,iterations = 3)

_, thresholded = cv2.threshold(diff, 0 , 255, cv2.THRESH_BINARY +cv2.THRESH_OTSU)
contours, _= cv2.findContours(thresholded,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
try:
if counter==0:
c=max(contours,key=cv2.contourArea)
mask = np.zeros(newThresh.shape[:2],np.uint8)
new_image = cv2.drawContours(mask,[c],0,255,-1,)
if cv2.contourArea(c)>1000 and len(contours)<=4:
if counter==0:
busyLED.on()
freeLED.off()
print("Possible object detcted")
counter=1
aa=0
print("set counter to 1")
continue
except Exception as e:
print(e)

Nag error siya ito po nakalagay sa shell;


Traceback (most recent call last):
File "/home/pi/Trash-Segregator/rongie.py", line 13, in <module>
classifier = vision.ImageClassifier.create_from_options(options)
File "/home/pi/.local/lib/python3.9/site-packages/tensorflow_lite_support/python/task/vision/image_classifier.py", line 88, in create_from_options
classifier = CppImageClassifier.create_from_options(
RuntimeError: Input tensor has type kTfliteFloat32: it requires specifying NormalizationOptions metadata to preprocess input images. = vision.ImageClassifier.create_from_options(options)
File "/home/pi/.local/lib/python3.9/site-packages/tensorflow_lite_support/python/task/vision/image_classifier.py", line 88, in create_from_options
classifier = CppImageClassifier.create_from_options(
RuntimeError: Input tensor has type kTfliteFloat32: it requires specifying NormalizationOptions metadata to preprocess input images.
 
Back
Top