How To Use Yolo txt Files For Detection? - python

import cv2
import json
def save_yolo_format(image_file, json_file, txt_file):
with open(json_file) as f:
chars = json.loads(f.read())
bgr = cv2.imread(image_file)
result = ""
for char in chars:
x_center = (char["x"] + char["width"] // 2) / bgr.shape[1]
y_center = (char["y"] + char["height"] // 2) / bgr.shape[0]
width = char["width"] / bgr.shape[1]
height = char["height"] / bgr.shape[0]
label = char["char_id"]
result += str(label) + " " + str(x_center) + " " + str(y_center) + " " + str(width) + " " + str(height) + "\n"
with open(txt_file, "w+") as f:
f.write(result)
save_yolo_format("dataset_root/images/1.jpg",
"dataset_root/labels/1.json",
"dataset_root/labels/1.txt")
**I Convert Json Files To Yolo Txt File **
After Run Code My Result Is...
One Of My Text File Value:
7 0.05197505197505198 0.5234375 0.07276507276507277 0.26953125
5 0.13097713097713098 0.51953125 0.08523908523908524 0.25390625
26 0.23700623700623702 0.51953125-0.12058212058212059 0.32421875
2 0.3471933471933472 0.5234375 0.08316008316008316 0.28125
How can I use the files above for detection?

Related

How do I make my number to excel coordinate converter work without if statements?

I have made a python program that recreates an image in excel by filling cells with different shades of red, green and blue. I have made this method to convert a number to a x coordinate in excel:
alph = [i for i in string.ascii_uppercase]
alph.insert(0,'')
def numToExcel(x):
stri = ''
row = x
rdiv26 = row//26
rdiv676 = row//676
stri += alph[(rdiv676)-((rdiv676)//676)*676]
stri += alph[(rdiv26)-((rdiv26)//26)*26]
stri += alph[1+(row%26)]
return stri
I added an empty space at the beginning so the program prints, for example, B3 instead of AAB3. However this means it does not reach for the letter Z. If i do x // 27 the image comes out wavy and it does not fix the issue.
This is my entire program:
import string
import time
import math
import openpyxl
from PIL import Image
from openpyxl import Workbook
from openpyxl.styles import Color, PatternFill, Font, Border
alph = [i for i in string.ascii_uppercase]
alph.insert(0,'')
def rgb_to_hex(r, g, b):
return '%02x%02x%02x' % (r,g,b)
def numToExcel(x):
stri = ''
row = x
rdiv26 = row//26
rdiv676 = row//676
stri += alph[(rdiv676)-((rdiv676)//676)*676]
stri += alph[(rdiv26)-((rdiv26)//26)*26]
stri += alph[1+(row%26)]
return stri
wb = Workbook()
ws = wb.active
im = Image.open('input.jpg')
pix = im.load()
x,y=im.size
start_time = time.time()
ct=0
for j in range(1,y-1):
i = 0
while i < 3*(x-1):
#Debug shi: print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y))
#Debug Shi: print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y*3) + " | (" + numToExcel(i) + "," + str(j) + ") -> (" + numToExcel(i+2) + "," + str(j) +") | " + str(pix[i/3,j][0])+','+str(pix[i/3,j][1])+','+str(pix[i/3,j][2]))
ws[numToExcel(i)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(pix[i/3,j][0],0,0))
ws[numToExcel(i+1)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(0,pix[i/3,j][1],0))
ws[numToExcel(i+2)+str(j)].fill = PatternFill("solid", fgColor=rgb_to_hex(0,0,pix[i/3,j][2]))
i += 3
ct += 3
#Progress Bar and stuff
print("\n"*100)
print("["+"#"*math.floor(20*(ct/(x*3*y)))+"-"*(20-math.floor(20*ct/(x*3*y)))+"] " + str(math.floor(ct/(x*3*y)*100))+"% "+ str(ct) + "/" + str(x*y*3) + " | Row " + str(j))
wb.save("sample2.xlsx")
print("--- Complete! ---\n--- %s seconds ---" % (time.time() - start_time))
And here is the output:
Please ignore any shitty code/math lol. I do not want to use any if statements because I am scared it would slow down the program.

Import equation from text file in Python

I have a complex equation which is generated into a .txt file. I would like to import this equation (which is all the text in the .txt file) and make a function from it, which can be subsequently fit.
Does anybody know how I might go about this? The equation to be fitted is at the the very bottom. My feeble attempt to import is below...
myfile1= open("dummyfile.txt", 'r')
def fcn(J1,J2,T,k,g):
return myfile1.read()
"dummyfile.txt" contents:
B**2*N*(12.0*g**2*sp.exp(2.0*J2/(T*k)) + 60.0*g**2*sp.exp(6.0*J2/(T*k)) + 168.0*g**2*sp.exp(12.0*J2/(T*k)) + 360.0*g**2*sp.exp(20.0*J2/(T*k)) + 30.0*g**2*sp.exp((2.0*J1 + 4.0*J2)/(T*k)) + 168.0*g**2*sp.exp((4.0*J1 + 8.0*J2)/(T*k)) + 360.0*g**2*sp.exp((6.0*J1 + 14.0*J2)/(T*k)) + 180.0*g**2*sp.exp((8.0*J1 + 12.0*J2)/(T*k)) + 660.0*g**2*sp.exp((8.0*J1 + 22.0*J2)/(T*k)) + 660.0*g**2*sp.exp((12.0*J1 + 18.0*J2)/(T*k)) + 1092.0*g**2*sp.exp((16.0*J1 + 26.0*J2)/(T*k)) + 546.0*g**2*sp.exp((18.0*J1 + 24.0*J2)/(T*k)) + 1680.0*g**2*sp.exp((24.0*J1 + 32.0*J2)/(T*k)) + 1224.0*g**2*sp.exp((32.0*J1 + 40.0*J2)/(T*k)))/(3*T*k*(6*sp.exp(2.0*J2/(T*k)) + 10*sp.exp(6.0*J2/(T*k)) + 14*sp.exp(12.0*J2/(T*k)) + 18*sp.exp(20.0*J2/(T*k)) + 5*sp.exp((2.0*J1 + 4.0*J2)/(T*k)) + 14*sp.exp((4.0*J1 + 8.0*J2)/(T*k)) + 18*sp.exp((6.0*J1 + 14.0*J2)/(T*k)) + 9*sp.exp((8.0*J1 + 12.0*J2)/(T*k)) + 22*sp.exp((8.0*J1 + 22.0*J2)/(T*k)) + 22*sp.exp((12.0*J1 + 18.0*J2)/(T*k)) + 26*sp.exp((16.0*J1 + 26.0*J2)/(T*k)) + 13*sp.exp((18.0*J1 + 24.0*J2)/(T*k)) + 30*sp.exp((24.0*J1 + 32.0*J2)/(T*k)) + 17*sp.exp((32.0*J1 + 40.0*J2)/(T*k)) + 1))
You can do that with exec().
Code:
def build_function(filename):
with open(filename, 'rU') as f:
eqn = f.read().strip()
exec("def fcn(J1, J2, T, k, g):\n return ({})".format(eqn))
return locals()['fcn']
Test Code:
fcn = build_function('file1')
print(fcn(1, 2, 3, 4, 5))
File1:
J2 + T*k
Results:
14

Read CSV file with hebrew text and write to PDF file using python

I am trying to read table from a csv file and write it to PDF file, but the Hebrew text is shown as a gibberish in the PDF file. When I try to add encode('utf-8') I got an error.
This is the code:
for line in list(open('aw.csv', encoding = "iso-8859-1")):
if len(line.strip()) != 0:
line = line.strip()
column = line.split(',')
if numrow == 0:
html_out1 = html_out1 + '<thead><tr><th width="10%">' + column[0] + '</th><th width="10%" >' + column[1] + '</th><th width="40%">' + column[2] + '</th><th width="40%">' + column[3] + '</th><th width="20%">' + column[4] + '</th></tr></thead>'
else:
print(column[4].encode('utf-8'))
html_out = html_out + '<tr><td>' + column[0] + "</td><td>" + column[1] + "</td><td>" + column[2] + "</td><td>" + column[3] + "</td><td>" + column[4] + "</td></tr>"
numrow = numrow + 1
from fpdf import FPDF, HTMLMixin
class MyFPDF(FPDF, HTMLMixin):
pass
html = html +html_out1 + html_out + "</tbody> </table>"
pdf = MyFPDF()
# First page
pdf.add_page()
pdf.write_html(html)
pdf.output('html.pdf', 'F')
How can I convert the gibberish to Hebrew?

Script Loop through files in directory

I have the following code which creates the txt file I require from a shp.file with the data I need. I have a folder called profiles containing a few number of shape files named (profil1.shp, profil2.shp, profil3.shp etc.). I was wondering how to create a loop so that the script creates for each file a txt file with the same name (eg. for profil1.shp create profil1.txt, profil2.shp create profil2.txt and so on).
import ogr, os, sys, osr
os.chdir('..\profiles')
file = open('profil1.txt', 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open('profil1.shp', 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
edit: the code is returning a Could not open file.Photo of the folder containing the files and their respective names. Safe to assume I am doing something wrong.
import ogr, os, sys, osr,os.path
os.chdir = ('C:\Users\Andrei\Desktop\profil3')
l = os.listdir('C:\Users\Andrei\Desktop\profil3')
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
You can use os.listdir() to list the files and folders in the current directory.
This returns a list of all files in the current directory (or the directory given to it as parameter , if no parameter is specified it checks the current directory) .
Then you can check for files with the name ending with .shp using string.endswith() function and then use that to create your new files.
Example of a small portion -
import os , os.path
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
At the end s1 would contain the file with extension as .txt .
Then you can do your logic on this file, and keep on doing like this.
Full code would look something like -
import ogr, os, sys, osr,os.path
os.chdir('..\profiles')
l = os.listdir()
for i in l:
if i.endswith('.shp'):
s1 = s.split('.')[0] + '.txt'
file = open(s1, 'w')
driver = ogr.GetDriverByName('ESRI Shapefile')
datasource = driver.Open(i, 0)
if datasource is None:
print 'Could not open file'
sys.exit(1)
layer = datasource.GetLayer()
feature = layer.GetNextFeature()
while feature:
id = feature.GetFieldAsString('ID')
Distanta = feature.GetFieldAsString('DIST')
Z = feature.GetFieldAsString('Z')
geom = feature.GetGeometryRef()
x = str(geom.GetX())
y = str(geom.GetY())
file.write(id + " " + Distanta + " " + "[X]:" + " " + x + ' ' + '[Y]:' + " " + y + " " + " " + "[Z]" + Z + " " + "\n")
feature.Destroy()
feature = layer.GetNextFeature()
datasource.Destroy()
file.close()
A better way of openning files, etc is using with statement. Look up its tutorial here.

Capture dB levels from a WAV file

Python 2.7.3 (default, Sep 26 2013, 16:35:25) [GCC 4.7.2] on linux2
Linux Mint 14
Using Python, I am reading a wav and putting the data to a text file. The entire script is below. It is my first Python Script.
The values for the micsec can be anything from 000000 to 999999. There are frequently leading zero's which I am stripping with lstrip('0').
If the value is 000000, I end up with null. I'm using an extra step to change null to 0.
What is the best way to do this in a single step ?
Thanks for any input.
!/usr/bin/python
import contextlib, datetime, math, os, time, wave, glob
from scipy.io.wavfile import read
from numpy import log10, sqrt, mean
import numpy as np
path = "/the/path/*.wav"
for fname in glob.glob(path):
print "process_wav is processing - " + fname
outfname = fname + ".txt"
mtime = datetime.datetime.fromtimestamp(os.path.getmtime(fname))
tm=0.000000
with contextlib.closing(wave.open(fname,'r')) as f:
channels = f.getnchannels()
sampwidth = f.getsampwidth()
comptype = f.getcomptype()
frames = f.getnframes()
rate = f.getframerate()
wav_duration = frames / float(rate)
frame_duration = round((wav_duration / frames),6)
samprate, wavdata = read(fname)
chunks = np.array_split(wavdata, frames)
hdr = (
"# audio file processed - " + fname +
"\n# this file name - " + outfname +
"\n# audio file mod time-" + str(mtime) +
"\n# channels - " + str(channels) +
"\n# sampwidth - " + str(sampwidth) +
"\n# comptype - " + str(comptype) +
"\n# frames - " + str(frames) +
"\n# rate - " + str(rate) +
"\n# wav_duration - " + str(wav_duration) +
"\n# frame_dutation - " + "{0:0.6f}".format(frame_duration) +
"\n# chunk|wave_file_name|audio_file_timestamp|chunk_second|chunk_microsecond|chunk_time_in_audio|frame_duration|dB\r\n"
)
out = open(outfname,'w')
out.write(hdr)
for i,chunk in enumerate(chunks):
try:
sec = int("{0:0.6f}".format(round(float(tm),6)).split('.')[0])
micsec = "{0:0.6f}".format(round(float(tm),6)).split('.')[1].lstrip('0')
#handle 000000 - there has to be a better way
micsec = int(float(micsec)) if len(micsec)>=1 else 0
cm = mtime + datetime.timedelta(seconds=sec,microseconds=micsec)
out.write("{}|{}|{}|{}|{}|{}|{}|{}\n".format(i, fname, mtime, sec, micsec, cm, frame_duration, 20*log10( sqrt(mean(chunk**2)))))
tm += frame_duration
except ValueError as ex:
print("value error" + str(ex))
out.write(str(i) + str(ex))
except Exception,e:
print("ERROR" + str(e))
out.write(str(i) + str(e))
out.close()

Categories

Resources