this is what i make in python server code (receiving data length from C client and then receiving image file(.jpg))
but problem is when i receiving data length error occurs "invaild base64-encoded string"
here is my servercode (Removed unnecessary functions) and when trying to run the stringData part the error occurs
import os
import socket
import cv2
import numpy
import base64
import glob
import sys
import time
import threading
from datetime import datetime
class ServerSocket:
def receiveImages(self):
cnt_str = ''
cnt = 0
try:
while True:
if (cnt < 10):
cnt_str = '000' + str(cnt)
elif (cnt < 100):
cnt_str = '00' + str(cnt)
elif (cnt < 1000):
cnt_str = '0' + str(cnt)
else:
cnt_str = str(cnt)
if cnt == 0: startTime = time.localtime()
cnt += 1
length = self.conn.recv(64)
print(length)
length1 = length.decode('utf-8')
print(length1)
stringData = self.recvall(self.conn, int(length1))
## stringData = self.conn.recv(100000)
##print(stringData)
msg = "ready"
self.conn.sendall(msg.encode())
stime = self.recvall(self.conn, 64)
print('send time: ' + stime.decode('utf-8'))
now = time.localtime()
print('receive time: ' + datetime.utcnow().strftime('%Y-%m-%d %H:%M:%S.%f'))
data = numpy.frombuffer(base64.b64decode(stringData), numpy.uint8)
decimg = cv2.imdecode(data, 1)
cv2.imshow("image", decimg)
cv2.imwrite('./' + str(self.TCP_PORT) + '_images' + str(self.folder_num) + '/img' + cnt_str + '.jpg', decimg)
cv2.waitKey(1)
if (cnt == 60 * 10):
cnt = 0
convertThread = threading.Thread(target=self.convertImage(str(self.folder_num), 600, startTime))
convertThread.start()
self.folder_num = (self.folder_num + 1) % 2
except Exception as e:
print(e)
#self.convertImage(str(self.folder_num), cnt, startTime)
self.socketClose()
cv2.destroyAllWindows()
self.socketOpen()
self.receiveThread = threading.Thread(target=self.receiveImages)
self.receiveThread.start()
def recvall(self, sock, count):
buf = b''
while count:
newbuf = sock.recv(count)
if not newbuf: return None
buf += newbuf
count -= len(newbuf)
return buf
def convertImage(self, fnum, count, now):
img_array = []
cnt = 0
for filename in glob.glob('./' + str(self.TCP_PORT) + '_images' + fnum + '/*.jpg'):
if (cnt == count):
break
cnt = cnt + 1
img = cv2.imread(filename)
height, width, layers = img.shape
size = (width, height)
img_array.append(img)
file_date = self.getDate(now)
file_time = self.getTime(now)
name = 'video(' + file_date + ' ' + file_time + ').mp4'
file_path = './videos/' + name
out = cv2.VideoWriter(file_path, cv2.VideqqoWriter_fourcc(*'.mp4'), 20, size)
for i in range(len(img_array)):
out.write(img_array[i])
out.release()
print(u'complete')
def main():
server = ServerSocket('ServerIP', PORT)
if __name__ == "__main__":
main()
what could it be the problems? in my expectation when decode the string data it can be the problem that C client encode causes problem
2 months ago i ordered 3 RBG Matrix panel + an ada fruit matrix bonnet for Raspberrypi to setup a matrix display showing my google Calendar. suddenly the display shows a big redstripe in the upper half of the display. i also cant control the brightness. if the brightness is to low nothing but the red stripe is visisible.i ordered a second copy of the bonnet hoping i incedently destroyed something while sodering or due to too high currents of my powersuply (actually 5V max 0.7A, used to be higher, 12v). at software level i tried i few different args with no difference.
here dome images
at the beginning of the project everything was fine, no stripe nothing, then suddenly
i use 1 matrix P4 matrix from adafruit and one without brand from ebay
thank you for helping me
regards Anika
currently use RGBMAtrix lib with
sudo python3 time.py --led-cols=64 --led-gpio-mapping=adafruit-hat-pwm --led-slowdown-gpio=5 --led-no-drop-privs --led-pwm-bits=1 --led-chain=2 --led-panel-type=FM6126A --led-pixel-mapper=Rotate:180
this i the python code for drive 2 matrixes in chain
#!/usr/bin/env python
# Display a runtext with double-buffering.
from samplebase import SampleBase
from rgbmatrix import graphics, RGBMatrix, RGBMatrixOptions
from datetime import datetime, timedelta
import requests, json, time, _thread
##################################################################################################
##################################################################################################
##################################################################################################
class Color():
GREEN = graphics.Color(0 , 255, 0)
BLACK = graphics.Color(0 , 0 , 0)
##################################################################################################
##################################################################################################
##################################################################################################
class Pref(SampleBase):
#TEXT_TIME_REVERSED = False
#FIRST_EVENT_DETAILS = False
INLINE_TIME = True
INLINE_TIME_COL = 6.5
BEGIN_SECOND_DETAIL = 60
MINUTE_COUNT_MAX = 60
MINUTE_BLINK_MAX = 15
NIGHT_OFF = 22
DAY_ON = 4
##################################################################################################
##################################################################################################
##################################################################################################
class MatrixCal(SampleBase):
def __init__(self, *args, **kwargs):
super(MatrixCal, self).__init__(*args, **kwargs)
#self.parser.add_argument("-t", "--text", help="The text to scroll on the RGB LED panel", default="Hello world!")
def run(self):
#make canvas and grafics
offscreen_canvas = self.matrix.CreateFrameCanvas()
secondary_canvas = self.matrix.CreateFrameCanvas()
#font
font_height = 8
font_width = 5
font = graphics.Font()
font.LoadFont("../../../fonts/5x8_custom.bdf")
global data, dt0
data = {"events":[], "annc":[], "todos":[]}
data_ttl = 1 #minute
data_error_retry = 10#mintes
#some vars
format_date_time_second = '%Y-%m-%dT%H:%M:%S'
format_time = "%H:%M"
pos = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
skip_next_event = False
screen_width = offscreen_canvas.width
screen_height = offscreen_canvas.height
screen_main = screen_width
if Pref.INLINE_TIME: screen_main = screen_width - font_width*Pref.INLINE_TIME_COL
tlen = 0
f_dub_ev = False
f_gehen_ev = False
f_no_blink = False
# DEF ###################################################################################
def drawText(_x, _y, _text, _color=Color.GREEN, _font=font):
return graphics.DrawText(offscreen_canvas, _font, _x, _y,_color, _text)
def drawLine(_x, _y, _w, _h, _color):
graphics.DrawLine(offscreen_canvas, _x, _y, _w, _h, _color)
def clearArea(x, y, w, h, _color=Color.BLACK):
for j in range(0, h):
graphics.DrawLine(offscreen_canvas, x, y+j, x+w-1, y+j, _color)
def showMinuteCount(time_diff, ev):
#show minutes count
if dt_start>dt0 and (time_diff<=Pref.MINUTE_COUNT_MAX or ('description' in ev and "display_type_duration" in ev['description'])):
if sec%2==0 and time_diff<=Pref.MINUTE_BLINK_MAX and not f_no_blink :
return ""
else:
if time_diff==0:return "jetzt"
else: return "ʼn{: >2d}mʼn".format(time_diff)
elif dt_start<dt0 or ('description' in ev and "display_type_duration" in ev['description']):
time_diff = int((dt_end-dt0).seconds/60)
if time_diff<=Pref.MINUTE_COUNT_MAX:
return str(time_diff) + "mʼn"
else:
if "schlafen" in ev['summary']:
return "noch " + str(dt_end-dt0)[0:4] +"h"
return "-"+dt_end.strftime("%H:%M")
else:
return dt_start.strftime("%H:%M")
def getData(a):
#api access
deploment_id = "THATS_CONFIDENTIAL"
access_token = "THAT_TOO"
url = "https://script.google.com/macros/s/"+deploment_id+"/exec?token="+access_token
next_data_load = datetime.now();
global data
while True:
#load data from api
dt0 = datetime.now()
if(dt0 > next_data_load):
print(dt0.strftime("%H:%M:%S") + " aquiring new data. next in " + str(data_ttl)+" Minute")
try:
r = requests.get(url)
r.raise_for_status()
data = json.loads(r.text)['data']
except requests.exceptions.HTTPError as errh:
print ("Http Error:",errh)
data['annc'].append({"type":"warning", "text":"HTTP " + str(errh.response.status_code) + " - Es gab ein Problem beim empfangen der Daten"})
except requests.exceptions.ConnectionError as errc:
print ("Error Connecting:",errc)
data['annc'].append({"type":"warning", "text":"Es gab ein Problem bei der Verbindung"})
except requests.exceptions.Timeout as errt:
print ("Timeout Error:",errt)
data['annc'].append({"type":"warning", "text":"Zeitüberschreitung beim laden der Daten"})
except requests.exceptions.RequestException as err:
print ("OOps: Something Else",err)
data['annc'].append({"type":"warning", "text":"Es gab ein Problem beim laden der Daten"})
except Exception as err:
print ("OOps: Something unexpected happend",err)
finally:
next_data_load = datetime.now() + timedelta(minutes=data_ttl);
#end if
time.sleep(1)
#end while
#end def getData
#def getWeather():
#Nachmittags wird es bewölkt. 🌡 min 13°C, max 23°C, ⌀ 20°C
#########################################################################################
#start data thread
_thread.start_new_thread(getData,(99,))
#data thread
while True:
offscreen_canvas.Clear()
if len(data['todos'])>0:screen_main=64
else: screen_main = screen_width
#determine whether main screen is large enought to display events with inline time
Pref.INLINE_TIME=screen_main>64;
#current date and time
dt0 = datetime.now()
sec = int(datetime.now().strftime("%S"))
hour = int(datetime.now().strftime("%H"))
ms = int(datetime.now().strftime("%f")[:-3])
#nacht abschaltung von helligkeit
#if False and Pref.NIGHT_OFF <= hour or hour < Pref.DAY_ON: self.matrix.brightness = 10
#else:
#self.matrix.brightness = 80
#reset screen vars
screen_y = font_height-1
detail_line = not Pref.INLINE_TIME
#print max 4 independet lines
index = 0
line = 0
#when no data available dim screen and only print time
if len(data['events'])==0:
#self.matrix.brightness = 10
graphics.DrawText(offscreen_canvas, font, screen_width-( 5 *font_width), font_height-1 ,Color.GREEN, datetime.now().strftime("%H:%M"))
else:
for todo in data['todos']:
t_title = todo['title']
if index==0:
clearArea(screen_main, 0, screen_width-screen_main, 8, Color.GREEN)
graphics.DrawText(offscreen_canvas, font, screen_width-( 12 *font_width), font_height-1 ,Color.BLACK, datetime.now().strftime("%d.%m. %H:%M"))
screen_y += font_height
#runtext optimization
if len(t_title)*font_width>screen_main-16: t_title = t_title+" "+t_title
else: pos[index+4] = screen_main + font_width+2
#display todo title
tlen = drawText(pos[index+4], screen_y, t_title)
clearArea(0, 8, screen_main+8, 32)
#move line if its longer then screen
if tlen > screen_main-16:
pos[index+4] -= 1
if (tlen/2-(font_width))*-1+screen_main+8> pos[index+4]:
pos[index+4] = screen_main + font_width+12
#graphics.DrawText(secondary_canvas, font, pos[index+4], screen_y ,Color.GREEN, todo['title'])
#graphics.DrawText(offscreen_canvas, font, screen_main+2, 15 ,Color.GREEN, "-")
graphics.DrawText(offscreen_canvas, font, screen_main+2, 15 ,Color.GREEN, "-")
if len(data['todos'])>1:graphics.DrawText(offscreen_canvas, font, screen_main+2, 23 ,Color.GREEN, "-")
if len(data['todos'])>2:graphics.DrawText(offscreen_canvas, font, screen_main+2, 31 ,Color.GREEN, "-")
drawLine(screen_main, 0, screen_main, screen_height, Color.GREEN)
screen_y += font_height
t_title = ""
index +=1
if screen_y>32:break
#end for todo
if len(data['todos'])>0:
clearArea(0, screen_main, screen_width-screen_main, screen_height)
#reset screen_y
screen_y = font_height-1
index =0
for ev in data['events']:
#events params
dt_start = datetime.strptime(ev['begin'][0:18], format_date_time_second)
dt_end = datetime.strptime(ev['end'][0:18], format_date_time_second)
time_diff = int((dt_start-dt0).seconds/60)
ev_summary = ev['summary']
#skip ended events or when event is from main cal and dark blue
if dt_end<=dt0 or time_diff==0 or ev_summary.startswith('#') or ('color' in ev and ev['color'] == 9): continue
#parallel events
b0 = data['events'][index]['begin']==data['events'][index+1]['begin']
b1 = (datetime.strptime(data['events'][index]['begin'][0:18], format_date_time_second)<dt0 and datetime.strptime(data['events'][index+1]['begin'][0:18], format_date_time_second)<dt0)
if (b0 or b1) and data['events'][index]['end']==data['events'][index+1]['end']:
f_dub_ev = True
index +=1 #skip ev
continue
#event details
if f_dub_ev: ev_summary = data['events'][index-1]['summary'] + " & " + ev_summary;
#skip gehen event and attach it to next event
if ev_summary.replace(">", "")=="gehen":
f_gehen_ev = True
data['events'][index+1]['travel_start'] = ev['begin']
continue
if ev_summary.startswith("-"):f_no_blink = True
#replace control chars
if ev_summary.startswith(">"):
#minute_blink_max = 15
ev_summary = ev_summary[1:len(ev_summary)]
ev_summary = ev_summary.replace(">>", "")
ev_summary = ev_summary.replace("schlafen>", "schlafen")
if f_no_blink:ev_summary = ev_summary[1:len(ev_summary)]
#runtext optimization
if len(ev_summary)*font_width>screen_main and (line>1 and f_dub_ev): ev_summary = ev_summary+" "+ev_summary
else: pos[line] = 0
#display main
tlen = drawText(pos[line], screen_y, ev_summary)
#move line if its longer then screen
if tlen > screen_main and (detail_line or Pref.INLINE_TIME):
pos[line] -= 1
if (tlen/2-(font_width))*-1>pos[line]:
pos[line] = font_width+4
#calculate time difference
# show second detail line when time time has come
if time_diff<=Pref.BEGIN_SECOND_DETAIL or dt_start<dt0 and dt_end>dt0: detail_line=not Pref.INLINE_TIME
if Pref.INLINE_TIME:
x = screen_width-( Pref.INLINE_TIME_COL *font_width)
clearArea(x, screen_y-7, Pref.INLINE_TIME_COL*font_width, font_height)
text = showMinuteCount(time_diff, ev)
x = screen_width-( len(text) *font_width)
drawText (x, screen_y, text)
if detail_line or Pref.INLINE_TIME:
if detail_line:
detail_line = False
screen_y += font_height
text = showMinuteCount(time_diff, ev)
if 'travel_start' in ev:
if Pref.INLINE_TIME: screen_y += font_height
blink_go = 15
if data['events'][index-1]['summary']=='>>>gehen': blink_go = 60
dt_travel = datetime.strptime(ev['travel_start'][0:18], format_date_time_second)
travel_diff = int((dt_travel-dt0).seconds/60)
hz=sec%20<=9
if travel_diff<=15: hz=sec%2==0;
#elif travel_diff<15: hz=sec%4<=1;
if Pref.INLINE_TIME:text = ""
else: text = " >"+text
if travel_diff <= Pref.MINUTE_COUNT_MAX:
if hz and travel_diff<=blink_go :
#text = text
if not Pref.INLINE_TIME:text = "gehen" + text
#wechsel blinken gehen mit zeit/"jetzt"
elif not Pref.INLINE_TIME:
if travel_diff==0: text="jetzt" + text
else: text= str(travel_diff) + "mʼn" + text
#wechsel blinken gehen in zeit/jetzt gehen mit leerzeile
elif Pref.INLINE_TIME:
if travel_diff<=0 : text="jetzt gehen"
else: text= "gehen ʼn{: >2d}mʼn".format(travel_diff)
elif not Pref.INLINE_TIME:
text = dt_travel.strftime("%H:%M") + text
else:
text = "gehen "+dt_travel.strftime("%H:%M")
#draw the text to the line
tl = int(len(text))
drawText( screen_main-( tl *font_width), screen_y, text)
#end if detail_line or Pref.INLINE_TIME:
f_dub_ev = False
f_gehen_ev = False
f_no_blink = False
#incrementation & loop break conditions
index +=1
line +=1
screen_y += font_height
if screen_y>screen_height:break
#end for
#end else of events len == 0
#annc = [{"type":"warning", "text":"Es dd"}]
#runtext announcement
if len(data['annc'])>0 and False:
#clear last line
clearArea(0, screen_height-font_height, screen_width, 8)
#get text, double it for smooth runtext animation
annc_text = data['annc'][0]['text']
annc_text = annc_text+" "+annc_text
alen = len(annc_text)*font_width
pos[-1] -= 1
if (alen/2-(2*font_width))*-1>pos[-1]:
pos[-1] = 2*font_width+4
graphics.DrawText(offscreen_canvas, font, pos[-1], screen_height-1 ,Color.GREEN, annc_text)
clearArea(0, screen_height-font_height, 8, 8)
#graphics.DrawText(offscreen_canvas, font, 0, screen_height-1 ,Color.GREEN, "ⓘ")
graphics.DrawText(offscreen_canvas, font, 0, screen_height-1 ,Color.GREEN, "⚠")
#offscreen_canvas = self.matrix.SwapOnVSync(secondary_canvas)
offscreen_canvas = self.matrix.SwapOnVSync(offscreen_canvas)
time.sleep(0.07)
#end while
#end def run(self)
# Main function
if __name__ == "__main__":
mcal = MatrixCal()
if (not mcal.process()):
mcal.print_help()
I'm uploading a file to the ftp server, the actual settings for the upload are correct but it isn't uploading the correct filename, it is uploading filename as the actual name of the file instead of capture......
#!/usr/bin/python
#
# Lightweight Motion Detection using python picamera libraries
# based on code from raspberry pi forum by user utpalc
# modified by Claude Pageau for this working example
# ------------------------------------------------------------
# original code on github https://github.com/pageauc/picamera-motion
# This is sample code that can be used for further development
verbose = True
if verbose:
print "Loading python libraries ....."
else:
print "verbose output has been disabled verbose=False"
import picamera
import picamera.array
import datetime
import time
import ftplib
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
from fractions import Fraction
#Constants
SECONDS2MICRO = 1000000 # Constant for converting Shutter Speed in Seconds to Microseconds
# User Customizable Settings
imageDir = "images"
imagePath = "/home/pi/pimotion/" + imageDir
imageNamePrefix = 'capture-' # Prefix for all image file names. Eg front-
imageWidth = 1980
imageHeight = 1080
imageVFlip = False # Flip image Vertically
imageHFlip = False # Flip image Horizontally
imagePreview = False
numberSequence = False
threshold = 10 # How Much pixel changes
sensitivity = 100 # How many pixels change
nightISO = 800
nightShutSpeed = 6 * SECONDS2MICRO # seconds times conversion to microseconds constant
# Advanced Settings not normally changed
testWidth = 100
testHeight = 75
def checkImagePath(imagedir):
# Find the path of this python script and set some global variables
mypath=os.path.abspath(__file__)
baseDir=mypath[0:mypath.rfind("/")+1]
baseFileName=mypath[mypath.rfind("/")+1:mypath.rfind(".")]
# Setup imagePath and create folder if it Does Not Exist.
imagePath = baseDir + imagedir # Where to save the images
# if imagePath does not exist create the folder
if not os.path.isdir(imagePath):
if verbose:
print "%s - Image Storage folder not found." % (progName)
print "%s - Creating image storage folder %s " % (progName, imagePath)
os.makedirs(imagePath)
return imagePath
def takeDayImage(imageWidth, imageHeight, filename):
if verbose:
print "takeDayImage - Working ....."
with picamera.PiCamera() as camera:
camera.resolution = (imageWidth, imageHeight)
# camera.rotation = cameraRotate #Note use imageVFlip and imageHFlip variables
if imagePreview:
camera.start_preview()
camera.vflip = imageVFlip
camera.hflip = imageHFlip
# Day Automatic Mode
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
camera.capture(filename)
sftp = ftplib.FTP('ftpdomainname','myftpusername','myftppassword') # Connect
fp = open(filename) # file to send
sftp.storbinary('STOR filename', fp) # Send the file
fp.close() # Close file and FTP
sftp.quit()
if verbose:
print "takeDayImage - Captured %s" % (filename)
return filename
def takeNightImage(imageWidth, imageHeight, filename):
if verbose:
print "takeNightImage - Working ....."
with picamera.PiCamera() as camera:
camera.resolution = (imageWidth, imageHeight)
if imagePreview:
camera.start_preview()
camera.vflip = imageVFlip
camera.hflip = imageHFlip
# Night time low light settings have long exposure times
# Settings for Low Light Conditions
# Set a frame rate of 1/6 fps, then set shutter
# speed to 6s and ISO to approx 800 per nightISO variable
camera.framerate = Fraction(1, 6)
camera.shutter_speed = nightShutSpeed
camera.exposure_mode = 'off'
camera.iso = nightISO
# Give the camera a good long time to measure AWB
# (you may wish to use fixed AWB instead)
time.sleep(10)
camera.capture(filename)
if verbose:
print "checkNightMode - Captured %s" % (filename)
return filename
def takeMotionImage(width, height, daymode):
with picamera.PiCamera() as camera:
time.sleep(1)
camera.resolution = (width, height)
with picamera.array.PiRGBArray(camera) as stream:
if daymode:
camera.exposure_mode = 'auto'
camera.awb_mode = 'auto'
else:
# Take Low Light image
# Set a framerate of 1/6 fps, then set shutter
# speed to 6s and ISO to 800
camera.framerate = Fraction(1, 6)
camera.shutter_speed = nightShutSpeed
camera.exposure_mode = 'off'
camera.iso = nightISO
# Give the camera a good long time to measure AWB
# (you may wish to use fixed AWB instead)
time.sleep( 10 )
camera.capture(stream, format='rgb')
return stream.array
def scanIfDay(width, height, daymode):
data1 = takeMotionImage(width, height, daymode)
while not motionFound:
data2 = takeMotionImage(width, height, daymode)
pCnt = 0L;
diffCount = 0L;
for w in range(0, width):
for h in range(0, height):
# get the diff of the pixel. Conversion to int
# is required to avoid unsigned short overflow.
diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
if diff > threshold:
diffCount += 1
if diffCount > sensitivity:
break; #break outer loop.
if diffCount > sensitivity:
motionFound = True
else:
# print "Sum of all pixels=", pxCnt
data2 = data1
return motionFound
def scanMotion(width, height, daymode):
motionFound = False
data1 = takeMotionImage(width, height, daymode)
while not motionFound:
data2 = takeMotionImage(width, height, daymode)
diffCount = 0L;
for w in range(0, width):
for h in range(0, height):
# get the diff of the pixel. Conversion to int
# is required to avoid unsigned short overflow.
diff = abs(int(data1[h][w][1]) - int(data2[h][w][1]))
if diff > threshold:
diffCount += 1
if diffCount > sensitivity:
break; #break outer loop.
if diffCount > sensitivity:
motionFound = True
else:
data2 = data1
return motionFound
def getFileName(imagePath, imageNamePrefix, currentCount):
rightNow = datetime.datetime.now()
if numberSequence :
filename = imagePath + "/" + imageNamePrefix + str(currentCount) + ".jpg"
else:
filename = "%s/%s%04d%02d%02d-%02d%02d%02d.jpg" % ( imagePath, imageNamePrefix ,rightNow.year, rightNow.month, rightNow.day, rightNow.hour, rightNow.minute, rightNow.second)
return filename
def motionDetection():
print "Scanning for Motion threshold=%i sensitivity=%i ......" % (threshold, sensitivity)
isDay = True
currentCount= 1000
while True:
if scanMotion(testWidth, testHeight, isDay):
filename = getFileName(imagePath, imageNamePrefix, currentCount)
if numberSequence:
currentCount += 1
if isDay:
takeDayImage( imageWidth, imageHeight, filename )
else:
takeNightImage( imageWidth, imageHeight, filename )
if __name__ == '__main__':
try:
motionDetection()
finally:
print ""
print "+++++++++++++++"
print "Exiting Program"
print "+++++++++++++++"
print ""
Instead of 'STOR filename', use the actual name of the file
sftp.storbinary('STOR ' + filename, fp)
So I've got a Python script that takes a bunch of images in a folder, and puts them together into arrays (like this). I also have another script that takes the frames of a video and puts them together in arrays. The problem is, the one that takes the frames from a video creates black bars between the images.
Here is the correct image made using the first script, which uses JPEGS:
Here is the wrong image made using the second script, which uses video frames:
Here is the script that makes the correct first image:
import Image
import glob
import os
name = raw_input('What is the file name (excluding the extension) of your video that was converted using FreeVideoToJPGConverter?\n')
x_res = int(raw_input('What do you want the width of your image to be (in pixels)?\n'))
y_res = int(raw_input('What do you want the height of your image to be (in pixels)?\n'))
rows = int(raw_input('How many rows do you want?\n'))
columns = int(raw_input('How many columns do you want?\n'))
images = glob.glob('./' + name + ' (*)/' + name + '*.jpg')
new_im = Image.new('RGB', (x_res,y_res))
x_cntr = 0
y_cntr = 0
if not os.path.exists('./' + name + ' Output/'):
os.makedirs('./' + name + ' Output/')
for x in xrange(0,len(images),1):
if x%(rows*columns) == 0:
new_im.save('./' + name + ' Output/' + str(x) + '.jpg')
new_im = Image.new('RGB', (x_res,y_res))
y_cntr = 0
x_cntr = 0
print str(round(100*(float(x)/len(images)), 1)) + "% Complete"
elif x%rows == 0:
x_cntr = 0
y_cntr = y_cntr + y_res/columns
elif x%1 == 0:
x_cntr = x_cntr + x_res/rows
im = Image.open(images[x])
im = im.resize((x_res/rows + x_res%rows, y_res/columns + y_res%columns), Image.ANTIALIAS)
new_im.paste(im, (x_cntr, y_cntr))
Here is the script that makes the incorrect second image:
import cv2, Image, os
name = raw_input('Video File (With Extension): ')
x_res = int(raw_input('Image Width (Pixels): '))
y_res = int(raw_input('Image Height (Pixels): '))
rows = int(raw_input('Number of Rows: '))
columns = int(raw_input('Number of Columns: '))
vidcap = cv2.VideoCapture(name)
success,im = vidcap.read()
frames = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
new_im = Image.new('RGB', (x_res, y_res))
x_cntr = 0
y_cntr = 0
print str(frames) + " Frames to Join"
if not os.path.exists('./' + name + ' Output/'):
os.makedirs('./' + name + ' Output/')
for x in xrange(0,frames,1):
if x%(rows*columns) == 0:
new_im.save('./' + name + ' Output/' + str(x) + '.jpg')
new_im = Image.new('RGB', (x_res,y_res))
y_cntr = 0
x_cntr = 0
print str(round(100*(float(x)/frames), 1)) + "% Complete"
elif x%rows == 0:
x_cntr = 0
y_cntr = y_cntr + y_res/columns
elif x%1 == 0:
x_cntr = x_cntr + x_res/rows
success,cv2_im = vidcap.read()
if success == True:
cv2_im = cv2.cvtColor(cv2_im,cv2.COLOR_BGR2RGB)
im = Image.fromarray(cv2_im)
im = im.resize((x_res/rows + x_res%rows, y_res/columns + y_res%columns), Image.ANTIALIAS)
new_im.paste(im, (x_cntr, y_cntr))
elif success == False:
new_im.save('./' + name + ' Output/' + str(x) + '.jpg')
print str(round(100*(float(x)/frames), 1)) + "% Complete" #Why isn't this 100%, fix
As you can see, this specific line for resizing the image (to fit the new array of images) is exactly the same in both scripts:
im = im.resize((x_res/rows + x_res%rows, y_res/columns + y_res%columns), Image.ANTIALIAS)
...Except in the first script, the image is opened from a JPEG, and in the second script, the image is taken from a video frame using OpenCV2. If I try this with a different video, the same thing happens. It resizes as if I were using .thumbnail instead of .resize.
So why is there a different output even though they are the same script?
PS: I also don't know why there are more output images on the jpeg script than the video script, but that may be the fault of FreeVideoToJPGConverter (a software); I'm not sure though.
I wrote a script in Python 2.6.2 that scans a directory for SVG's and resizes them if they are too large. I wrote this on my home machine (Vista, Python 2.6.2) and processed a few folders with no problems. Today, I tried this on my work computer (XP SP2, Python 2.6.2) and I get IOErrors for every file, even though files are in the directory. I think I've tried everything, and am unsure where to go from here. I am a beginner so this may be something simple. Any help would be appreciated.
import xml.etree.ElementTree as ET
import os
import tkFileDialog
#--------------------------------------
#~~~variables
#--------------------------------------
max_height = 500
max_width = 428
extList = ["svg"]
proc_count = 0
resize_count = 0
#--------------------------------------
#~~~functions
#--------------------------------------
def landscape_or_portrait():
resize_count +=1
if float(main_width_old)/float(main_height_old) >= 1.0:
print "picture is landscape"
resize_width()
else:
print "picture is not landscape"
resize_height()
return
def resize_height():
print "picture too tall"
#calculate viewBox and height
viewBox_height_new = max_height
scaleFactor = (float(main_height_old) - max_height)/max_height
viewBox_width_new = float(main_width_old) * scaleFactor
#calculate main width and height
main_height_new = str(viewBox_height_new) + "px"
main_width_new = str(viewBox_width_new) + "px"
viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new)
inputFile = file(tfile, 'r')
data = inputFile.read()
inputFile.close()
data = data.replace(str(tmain_height_old), str(main_height_new))
data = data.replace(str(tmain_width_old), str(main_width_new))
#data = data.replace(str(tviewBox), str(viewBox))
outputFile = file(tfile, 'w')
outputFile.write(data)
outputFile.close()
return
def resize_width():
print "picture too wide"
#calculate viewBox width and height
viewBox_width_new = max_width
scaleFactor = (float(main_width_old) - max_width)/max_width
viewBox_height_new = float(main_height_old) * scaleFactor
#calculate main width and height
main_height_new = str(viewBox_height_new) + "px"
main_width_new = str(viewBox_width_new) + "px"
viewBox = "0 0 " + str(viewBox_width_new) + " " + str(viewBox_height_new)
inputFile = file(tfile, 'r')
data = inputFile.read()
inputFile.close()
data = data.replace(str(tmain_height_old), str(main_height_new))
data = data.replace(str(tmain_width_old), str(main_width_new))
#data = data.replace(str(tviewBox), str(viewBox))
outputFile = file(tfile, 'w')
outputFile.write(data)
outputFile.close()
return
#--------------------------------------
#~~~operations
#--------------------------------------
path = tkFileDialog.askdirectory()
for tfile in os.listdir(path):
#print tfile
t2file = tfile
if tfile.find(".") >= 0:
try :
if t2file.split(".")[1] in extList:
print "now processing " + tfile
tree = ET.parse(tfile)
proc_count+=1
# Get the values of the root(svg) attributes
root = tree.getroot()
tmain_height_old = root.get("height")
tmain_width_old = root.get("width")
tviewBox = root.get("viewBox")
#clean up variables, remove px for float conversion
main_height_old = tmain_height_old.replace("px", "", 1)
main_width_old = tmain_width_old.replace("px", "", 1)
#check if they are too large
if float(main_height_old) > max_height or float(main_width_old) > max_width:
landscape_or_portrait()
except Exception,e:
print e
It looks to me like you are missing a os.path.join(path, tfile) to get the full path to the file you want to open. Currently it should only work for files in the current directory.
Perhaps it's a security issue? Perhaps you don't have the rights to create files in the folder