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
Related
import re
import socket
import sys
def Check(ip,port):
try:
s = socket.socket()
s.settimeout(0.3)
s.connect((ip,port))
return s.recv(512)
except:
pass
def Scan():
start = sys.argv[1]
end = sys.argv[2]
endip = end.partition('.')
currentip = start.split('.')
while not (currentip == endip):
targetip = currentip[0]+"."+currentip[1]+"."+currentip[2]+"."+currentip[3]
print("Checking: "+targetip+"\n")
result = Check(targetip,21)
if result:
if re.search("FTP",result.decode('utf-8')):
retard = open('ftps.txt','a')
retard.write(targetip+"\n")
retard.close()
if (int(currentip[3]) < 255) and (int(currentip[0]) != int(endip[0])) and (int(currentip[1]) != int(endip[1])) and (int(currentip[2]) != int(endip[2])) and (int(currentip[3]) != int(endip[3])+1):
int(currentip[3]) += 1
elif (int(currentip[3]) == 255) and (int(currentip[0]) != int(endip[0])) and (int(currentip[1]) != int(endip[1])) and (int(currentip[2]) != int(endip[2])) and (int(currentip[3]) != int(endip[3])+1):
if (int(currentip[2]) < 255):
int(currentip[2]) += 1
int(currentip[3]) = 0
elif (int(currentip[2]) == 255):
if (int(currentip[1]) < 255):
int(currentip[1]) += 1
int(currentip[2]) = 0
int(currentip[3]) = 0
elif (int(currentip[0]) < int(endip[0])) and (int(currentip[0]) != 255) and (int(currentip[1]) == 255):
int(currentip[0]) += 1
int(currentip[1]) = 0
int(currentip[2]) = 0
int(currentip[3]) = 0
Scan()
int(currentip[0]) += 1 causes an error while the conversion of other items that are exactly the same way converted trigger none.
File "ftpscan.py", line 46
int(currentip[0]) += 1
^
SyntaxError: cannot assign to function call
Basically, i += 1, is same as i = i + 1
in your case
int(currentip[0]) += 1 , is same as int(currentip[0]) = int(currentip[0]) + 1
So, technically you can't assign to the function call.
Instead, this should work
currentip[0] = int(currentip[0]) + 1
You are trying to increment a number (what int() returns) as opposed to the contents of a variable.
"""
FTPScan by StYl3z
Greetz fly out to:
L0rd,Legolas,Prometheus,Smoky-Ice,izibitzi,Waterb0ng,MaXtOr
usage: python3 ftpscan.py <startip> <endip>
"""
import re
import socket
import sys
def Check(ip,port):
try:
s = socket.socket()
s.settimeout(0.3)
s.connect((ip,port))
return s.recv(512)
except:
pass
def Scan():
start = sys.argv[1]
end = sys.argv[2]
endip = end.split('.')
currentip = start.split('.')
while not (currentip == endip):
targetip = currentip[0]+"."+currentip[1]+"."+currentip[2]+"."+currentip[3]
print("Checking: "+targetip+"\n")
result = Check(targetip,21)
if result == 0:
if re.search("FTP",result.decode('utf-8')):
retard = open('ftps.txt','a')
retard.write(targetip+"\n")
retard.close()
if not (int(currentip[3])==255):
currentip[3] = int(currentip[3])+1
currentip[3] = str(currentip[3])
else:
if not(int(currentip[2])==255):
currentip[2] = int(currentip[2])+1
currentip[2] = str(currentip[2])
currentip[3] = str("0")
else:
if not(int(currentip[1])==255):
currentip[1] = int(currentip[1])+1
currentip[1] = str(currentip[1])
currentip[2] = str("0")
currentip[3] = str("0")
else:
if not(int(currentip[0])==255):
currentip[0] = int(currentip[0])+1
currentip[0] = str(currentip[0])
currentip[1] = str("0")
currentip[2] = str("0")
currentip[3] = str("0")
Scan()
is the way it's working, thanks for trying to help me, i figured it out myself
i = 2 #int
cv2.imwrite([r'C:\Users\Desktop\result (' + str(i) + ').png'], result) #result is 16bit image
I want to save image under the name 'result (2).png'
Because, i is stuck in 'for loop'.
However, the code above causes an error.
Please help me.
add)
## Flat Field Correction (FFC) ##
import numpy as np
import cv2
import matplotlib.pyplot as plt
import numba as nb
import multiprocessing as multi
import parmap
import time
start = time.time()
B = cv2.imread(r'D:\remedi\Exercise\Xray\Offset.png', -1) # offset image
for i in range(2,3):
org_I = cv2.imread(r'D:\remedi\Exercise\Xray\objects\object (' + str(i) + ').png', -1) # original image
w = cv2.imread(r'D:\remedi\Exercise\Xray\white\white (' + str(i) + ').png', -1) # white image
## dead & bad pixel correction
corrected_w = w.copy()
corrected_org_I = org_I.copy()
c = np.mean(corrected_w)
p = np.abs(corrected_w - c)
sens = 0.7
[num_y, num_x] = np.where((p < c*sens) | (p > c*sens))
#[num_y, num_x] = np.where((corrected_w < c*0.97) | (corrected_w > c*1.03))
ar = np.zeros((3,3))
ar2 = np.zeros((3,3))
#pool = multi.Pool(processes=6)
iter = num_y.shape[0]
for n in range(iter):
#parmap.map(bad_pixel_correction, [n, num_y, num_x, ar, ar2, corrected_w, corrected_org_I], pm_pbar=True, pm_processes=6)
for j in range(-1,2):
for k in range(-1,2):
if num_y[n]+j == -1 or num_x[n]+k == -1 or num_y[n]+j == 576 or num_x[n]+k == 576:
ar[j+1][k+1] = 0
ar2[j+1][k+1] = 0
else:
ar[j+1][k+1] = corrected_w[num_y[n]+j][num_x[n]+k]
ar2[j+1][k+1] = corrected_org_I[num_y[n]+j][num_x[n]+k]
ar[1][1] = 0
ar2[1][1] = 0
corrected_w[num_y[n]][num_x[n]] = np.sum(ar)/np.count_nonzero(ar)
corrected_org_I[num_y[n]][num_x[n]] = np.sum(ar2)/np.count_nonzero(ar2)
c = np.mean(corrected_w) # constant
## flat field correction
FFC = np.uint16(np.divide(c*(corrected_org_I-B), (corrected_w-B)))
F = np.fft.fft2(FFC)
Fshift = np.fft.fftshift(F)
magnitude_spectrum3 = 20*np.log(np.abs(Fshift))
[row, col] = org_I.shape
[row2, col2] = np.array([row, col], dtype=np.int) // 2
row2_range = 1
col2_range = 2
Fshift[:row2-row2_range-1, col2-col2_range-1:col2+col2_range] = 0
Fshift[row2+row2_range:, col2-col2_range-1:col2+col2_range] = 0
fishift = np.fft.ifftshift(Fshift)
result = np.fft.ifft2(fishift)
print("time :", time.time() - start)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_org_I (' + str(i) + ').png', result)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_org_I (' + str(i) + ').png', corrected_org_I)
cv2.imwrite(r'C:\Users\jhjoo\Desktop\corrected_w (' + str(i) + ').png', corrected_w)
cv2.imwrite takes first argument as a string, not a list. You should fix your code as following:
cv2.imwrite(r'C:\Users\Desktop\result (' + str(i) + ').png', result) #result is 16bit image
I have a custom object detection code written in Python using Yolo. I want to write some output values like the image_name, detected_object_label,box_co-ordinate values, confidence percentage into 2 csv files. 1 csv should have image_name, detected_object_label,confidence percentage and the other should have image_name, detected_object_label,box_co-ordinate values
I have made the code for custom object detection till now.
import cv2
import glob
from glob import glob
import os
import shutil
import numpy as np
import argparse
import imutils
from keras.preprocessing.image import img_to_array
from keras.models import load_model
#import tensorflow as tf
from PIL import Image
import json
import sys
import csv
#from utils import label_map_util
#from utils import visualization_utils as vis_util
from os.path import isfile,join
import pandas as pd
########################################## EXTRACT FRAMES FROM VIDEO###########################
def extractFrames(m):
global vid_name
global img_name
vid_files=glob(m)
complete_videos = get_completed_videos()
new_vid_files = [x for x in vid_files if get_vid_name(x) not in complete_videos]
for vid in new_vid_files:
print("path of video========>>>>.",vid)
v1 = os.path.basename(vid)
try:
vid_name = get_vid_name(vid)
vidcap = cv2.VideoCapture(vid)
except cv2.error as e:
print(e)
except:
print('error')
fsize = os.stat(vid)
print('=============size of video ===================:' , fsize.st_size)
try:
if ( fsize.st_size > 1000 ):
fps = vidcap.get(cv2.CAP_PROP_FPS) # OpenCV2 version 2 used "CV_CAP_PROP_FPS"
frameCount = int(vidcap.get(cv2.CAP_PROP_FRAME_COUNT))
duration = frameCount/fps
minutes = int(duration/60)
print('fps = ' + str(fps))
print('number of frames = ' + str(frameCount))
print('duration (S) = ' + str(duration))
if (duration <= 5):
success,image = vidcap.read()
count=0
success=True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count % 10 == 0 or count ==0:
target_non_target(img_name, image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 5 and duration <= 10):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%20 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 10 and duration <= 20):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%30 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 20 and duration <= 100):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%50 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 100 and duration <= 300):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%100 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 300 and duration <= 600):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%150 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 600 and duration <= 900):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%300 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 900 and duration <= 1200):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%600 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 1200 and duration <= 1800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%900 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 1800 and duration <= 3600):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%1200 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 3600 and duration <= 7200):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%1500 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 7200 and duration <= 10800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%2000 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
elif (duration > 10800):
success,image = vidcap.read()
count = 0
success = True
while success:
img_name = vid_name + '_f' + str(count) + ".jpg"
success,image = vidcap.read()
if count%2500 == 0 or count == 0:
target_non_target(img_name,image)
count+=1
vidcap.release()
cv2.destroyAllWindows()
else:
print("video length exceeds max limit")
except:
print("error")
print('finished processing video ', vid)
with open('C:\\Python35\\target_non_target\\'+'video_info.csv', 'a') as csv_file:
fieldnames = ['Video_Name','Process']
file_is_empty = os.stat('C:\\Python35\\target_non_target\\'+'video_info.csv').st_size == 0
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
if file_is_empty:
writer.writeheader()
writer.writerow({'Video_Name':vid_name,'Process':'done'})
#print('finished processing video {0} with frames {1}'.format(vid_files[v_f], count))
def get_vid_name(vid):
return os.path.splitext(os.path.basename(vid))[0]
def get_completed_videos():
completed_videos = []
with open("C:\\Python35\\target_non_target\\video_info.csv") as csv_file:
for row in csv.reader(csv_file):
for col in range(0,len(row)):
try:
completed_videos.append(row[col])
except Exception as e:
print(str(e))
print(completed_videos[0])
return completed_videos
###########################CHECK FOR TARGET IMAGES FROM FRAMES###########################
def target_non_target(img_name, image):
try:
image_re = cv2.resize(image, (28, 28))
image_fl = image_re.astype("float") / 255.0
image_arr = img_to_array(image_fl)
image_expanded = np.expand_dims(image_arr, axis=0)
model_file = "C:\\Python35\\target_non_target\\target_non_target.model"
model = load_model(model_file)
(non_target, target) = model.predict(image_expanded)[0]
if target > non_target:
print("[INFO] Target DETECTED...")
#recognize_object(image)
draw_pred(image, class_ids[i], confidences[i], round(x), round(y), round(x + w), round(y + h))
else:
print("[INFO] NON TARGET...")
except Exception as e:
print(str(e))
#################################OBJECT RECOGNITION MODEL CODE################################
#def recognize_object(image):
yolo_cfg = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\yolov3-tiny.cfg"
weights = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\yolov3-tiny_final.weights"
class_names = "C:\\Python35\\custom_yolo_object_detector\\darknet\\custom\\objects.names"
def getOutputsNames(net):
layersNames = net.getLayerNames()
return [layersNames[i[0] - 1] for i in net.getUnconnectedOutLayers()]
def draw_pred(image, class_id, confidence, x, y, x_plus_w, y_plus_h):
label = str(classes[class_id])
color = COLORS[class_id]
cv2.rectangle(img, (x,y), (x_plus_w,y_plus_h), color, 2)
cv2.putText(img, label, (x-10,y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2)
classes = None
with open(class_names, 'r') as f:
classes = [line.strip() for line in f.readlines()]
print(classes)
COLORS = np.random.uniform(0, 255, size=(len(classes), 3))
net = cv2.dnn.readNet(weights,yolo_cfg)
image=cv2.resize(image, (299, 299))
blob = cv2.dnn.blobFromImage(image, 1.0/255.0, (299,299), [0,0,0], True, crop=False)
Width = image.shape[1]
Height = image.shape[0]
net.setInput(blob)
outs = net.forward(getOutputsNames(net))
class_ids = []
confidences = []
boxes = []
conf_threshold = 0.5
nms_threshold = 0.4
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > 0.5:
center_x = int(detection[0] * Width)
center_y = int(detection[1] * Height)
w = int(detection[2] * Width)
h = int(detection[3] * Height)
x = center_x - w / 2
y = center_y - h / 2
class_ids.append(class_id)
confidences.append(float(confidence))
boxes.append([x, y, w, h])
indices = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, nms_threshold)
for i in indices:
i = i[0]
box = boxes[i]
x = box[0]
y = box[1]
w = box[2]
h = box[3]
#draw_pred(obj_img, class_ids[i], confidences[i], round(x), round(y), round(x+w), round(y+h))
cv2.putText(image, label, (0, 15), cv2.FONT_HERSHEY_SIMPLEX, .6, (255, 0, 0))
cv2.imshow(image)
if __name__ == "__main__":
x="C:\\Python36\\videos\\*.mp4"
extractFrames(x)
You could pass in your values to this function
def writeToCSV(value1,value2,value3...):
with open('new.csv', 'a') as writeFile:
writer = csv.writer(writeFile)
for i in range(len(result)):
writer.writerow(result)
import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = ord(source_string[count + 1]) * 256 + ord(source_string[count])
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + ord(source_string[len(source_string) - 1])
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * 'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = []
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.append(ip)
file = open(file_name, 'w')
file.write(str(hosts))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '200.131.0.0/20' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(unicode(ips), strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()
I tried:
ip_network = ipaddress.ip_network( ips, strict=False) instead of ip_network = ipaddress.ip_network(unicode(ips), strict=False)
because of the error: ""NameError: name 'unicode' is not defined"
after:
I got: my_checksum = checksum(header + data) -> TypeError: can't concat bytes to str
so I tried:
data = bytes(192 * 'Q').encode('utf8') instead of data = 192 * 'Q'
Now, the error is : ""data = bytes (192 * 'Q').encode('utf8') TypeError: string argument without an encoding"
Could anyone help me to port the code to Python 3 ?
import random
import socket
import time
import ipaddress
import struct
from threading import Thread
def checksum(source_string):
sum = 0
count_to = (len(source_string) / 2) * 2
count = 0
while count < count_to:
this_val = source_string[count + 1] * 256 + source_string[count]
sum = sum + this_val
sum = sum & 0xffffffff
count = count + 2
if count_to < len(source_string):
sum = sum + source_string[len(source_string) - 1]
sum = sum & 0xffffffff
sum = (sum >> 16) + (sum & 0xffff)
sum = sum + (sum >> 16)
answer = ~sum
answer = answer & 0xffff
answer = answer >> 8 | (answer << 8 & 0xff00)
return answer
def create_packet(id):
header = struct.pack('bbHHh', 8, 0, 0, id, 1)
data = 192 * b'Q'
my_checksum = checksum(header + data)
header = struct.pack('bbHHh', 8, 0, socket.htons(my_checksum), id, 1)
return header + data
def ping(addr, timeout=1):
try:
my_socket = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
except Exception as e:
print (e)
packet_id = int((id(timeout) * random.random()) % 65535)
packet = create_packet(packet_id)
my_socket.connect((addr, 80))
my_socket.sendall(packet)
my_socket.close()
def rotate(addr, file_name, wait, responses):
print ("Sending Packets", time.strftime("%X %x %Z"))
for ip in addr:
ping(str(ip))
time.sleep(wait)
print ("All packets sent", time.strftime("%X %x %Z"))
print ("Waiting for all responses")
time.sleep(2)
# Stoping listen
global SIGNAL
SIGNAL = False
ping('127.0.0.1') # Final ping to trigger the false signal in listen
print (len(responses), "hosts found!")
print ("Writing File")
hosts = set()
for response in sorted(responses):
ip = struct.unpack('BBBB', response)
ip = str(ip[0]) + "." + str(ip[1]) + "." + str(ip[2]) + "." + str(ip[3])
hosts.add(ip)
with open(file_name, 'w') as file:
file.write('\n'.join(sorted(hosts, key=lambda item: socket.inet_aton(item))))
print ("Done", time.strftime("%X %x %Z"))
def listen(responses):
global SIGNAL
s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP)
s.bind(('', 1))
print ("Listening")
while SIGNAL:
packet = s.recv(1024)[:20][-8:-4]
responses.append(packet)
print ("Stop Listening")
s.close()
SIGNAL = True
responses = []
ips = '192.168.1.0/28' # Internet network
wait = 0.002 # Adjust this based in your bandwidth (Faster link is Lower wait)
file_name = 'log1.txt'
ip_network = ipaddress.ip_network(ips, strict=False)
t_server = Thread(target=listen, args=[responses])
t_server.start()
t_ping = Thread(target=rotate, args=[ip_network, file_name, wait, responses])
t_ping.start()
I have tried the following Python code on a dual monitor system (Windows7) to repeatedly save screenshots.
It generates 33 shots of 14.6MB (total 482MB) and then crash. Checking with Process Explorer I can see the amount of used memory raise to about 500MB.
My question is how to stop the memory leak?
import win32gui, win32ui, win32con, win32api
import time
import os
def my_capture(file_name):
hwin = win32gui.GetDesktopWindow()
width = win32api.GetSystemMetrics(win32con.SM_CXVIRTUALSCREEN)
height = win32api.GetSystemMetrics(win32con.SM_CYVIRTUALSCREEN)
left = win32api.GetSystemMetrics(win32con.SM_XVIRTUALSCREEN)
top = win32api.GetSystemMetrics(win32con.SM_YVIRTUALSCREEN)
hwindc = win32gui.GetWindowDC(hwin)
srcdc = win32ui.CreateDCFromHandle(hwindc)
memdc = srcdc.CreateCompatibleDC()
bmp = win32ui.CreateBitmap()
bmp.CreateCompatibleBitmap(srcdc, width, height)
memdc.SelectObject(bmp)
memdc.BitBlt((0, 0), (width, height), srcdc, (left, top), win32con.SRCCOPY)
bmp.SaveBitmapFile(memdc, file_name) # 'screenshot.bmp'
def captureAndSave(i):
if i < 10:
tmpStr = "00000" + str(i)
elif i < 100:
tmpStr = "0000" + str(i)
elif i < 1000:
tmpStr = "000" + str(i)
elif i < 10000:
tmpStr = "00" + str(i)
elif i < 100000:
tmpStr = "0" + str(i)
else:
tmpStr = str(i)
my_capture(tmpStr + '.bmp')
def myMainLoop():
i = 0
while 1:
i = i + 1
captureAndSave(i)
time.sleep(0.2)
#-----------------------------------------------------------------------------
if __name__ == '__main__':
try:
myMainLoop() # capure all monitor windows
except KeyboardInterrupt:
pass
I got the base code from: Python windows 7 screenshot without PIL:
You'll want to clean up your bitmaps and DCs, adding something like this after the bitmap is saved;
win32gui.DeleteObject(bmp.GetHandle())
memdc.DeleteDC()
srcdc.DeleteDC()
win32gui.ReleaseDC(hwin, hwindc)