Passing On Values Between Functions - python

Hi i'm working on a program where a user selects an image, then it gets turned into an ASCII version of the picture, which displays in both the console and then gets saved to a notepad .txt file. The code below currently does this but I think the way I am using my returns in the functions is messing up the code. Instead of asking for the image and background colour once, it asks for it 3 times before actually drawing out the ASCII image. Then after it has drawn it, it again asks for a 4th time for the image and background colour, before finally asking for the name to give the .txt file then creating the text file.
How do I change this so that it only asks each question once without repeating itself(and what exactly is this happening?). Thanks
def inputs():
image = input('What image file?')
return (image)
def pictureConvert():
a = inputs()
# codefollows

Call the inputs function only once, and store that everywhere. This ensures that the user will be asked for input only once:
def inputs():
image = input('What image file?')
return (image)
def pictureConvert():
a = inputs()
# codefollows

Related

Audio Detection for Python

I wanted to make a python program which detects system audio. Just like open-cv match template, is there any module which can detect a certain "characteristic" of an image (or audio for my case) and we can set a threshold value, and if the threshold value is crossed, we can pass a function. Basically, I am making this program for fishing in Minecraft. There is a mod which "pings" me or makes a sound whenever a fish is stuck in the fishing rod. I wanted to input and save the sound in the program (which can be easily done using modules) and see if the audio passes a certain threshold value in order to carry out the process of right clicking the mouse (which can be done by pyautogui module). I want this program to run infinitely until I press a key (which can be done using keyboard.is_pressed("ctrl") ).
I tried googling for a solution but due to my near to no knowledge of sound processing, I was unable to come to a solution. A logic for doing the infinite loop thing was to change the input setting in windows to system sounds and then recording and saving an audio wave file every five seconds and as soon as the file is saved, the program "tries" (try and except block) to delete its previous file in order to save storage and processing the current sound in the same loop.
Following is a sample code I made using open-cv using image detection:
(NOTE: You don't necessarily need to look into this code to solve my problem, this is just for an idea and I want a similar code but with audio instead of image detection)
import cv2 as cv
import os
import pyautogui
import time
from PIL import ImageGrab
import keyboard
path_1 = r"C:\Users\Aditya\AppData\Roaming\.minecraft\screenshots\2022-12-21_11.37.40 - Copy.png" #path_1 is the path of the "template" i.e. the image that I am trying to detect on the screen
threshold = 50672740 #this number was obtained after experimentally testing
path = "C:\\Users\\Aditya\\Documents\\fishing_pics\\"
#path variable is the path where the screenshots are being saved
n = len(os.listdir(path))+1
while keyboard.is_pressed("ctrl")==False:
filename = path+str(n)+".png"
prev2_filename = path+str(n-2)+".png"
n+=1
screenshot = ImageGrab.grab()
screenshot.save(filename,"PNG")
try:
os.remove(prev2_filename)
except:
print (prev2_filename+" doesn't exists")
haystack_img = cv.imread(filename,0)
needle_img = cv.imread(path_1,0)
haystack_img = cv.cvtColor(haystack_img,cv.COLOR_BGR2GRAY)
needle_img = cv.cvtColor(needle_img,cv.COLOR_BGR2GRAY)
result = cv.matchTemplate(needle_img,haystack_img,cv.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv.minMaxLoc(result)
if max_val>=threshold:
pyautogui.click(button='right')
time.sleep(1)
pyautogui.click(button='right')
time.sleep(0.1)
for file_name in os.listdir(path):
file = path + file_name
os.remove(file)
#this is used to remove any file left in the folder where screenshots are saved in order to save strorage
LOGIC >>> Ignore variable "n" because its just used to name the file as 1.png,2.png,etc...
I am capturing and saving a picture of my screen using ImageGrab from Pillow (PIL) and then comparing it to the template image in order to get a threshold value and if the threshold value is greater than a certain value (set by me) then it performs a function

How to change my script from an input in python

I have a list of images with the following names 47A, 33B, 2C, etc all alphnumeric with characters length until 10. The extension of all images is .png
I've created a python program to read one by one this images and extract information (contours area etc etc ). To do this, inside the script I always use the replacement crtl + H to change the names in the following codes:
#open image
img = cv2.imread("A.png", 0) in this case A is the name of an image
#save image
cv2.imwrite("A_copy.png", img)
#assign name into ID column
dframe['ID'] = 'A'
#save data into this path
dframe.to_csv(r'D:\\NBC_new2020_\\data\\A_data.txt', index = False, sep='\t')
I'm trying to open an image, save image, assign name to ID column and save the dataframe by changing the A to 47B and run the program then for 33B and run the program etc etc with replace crtl + H in the script.
For the moment is the only way to change it.
Is there any other way to change it? I was trying with the following code:
A = input('Insert the name of file in png extension:')
A = str(A)
47
img = cv2.imread("A.png", 0)
###########################################################
The A value is considered as a string but the program doesn"t allow to run it well
I would like to know how to replace the "A" as an input before start the python program (like ask me as an input)
Someone please help?
Thanks
You should replace "A.png" with A + ".png".
When inside quotes, everything is treated as their literal string value. You can concatenate strings with the plus operator to use variables.

Saving variable name using the .save function in Python

I'm currently working on converting breastcancer scans into black and white photos. This code needs to scan every file in the directory, process it, and save it with a unique name. My code looks like this:
wd = os.getcwd()
lencounter = 0
for file in os.listdir(wd):
lencounter += 1
for x in range(lencounter):
for file in os.listdir(wd):
if file.endswith("class0.png"):
image_file = Image.open(file)
image_file= image_file.convert('L')
image_file= image_file.convert('1')
print(image_file, x)
image_file.save("result1.png")
This code only allows me to save the last transformed picture, as "result1". Somehow the .save function doesn't let me include any iterationumber, just like you would expect when using the write() function.
I need something like "originalname_blackandwhite1.png" for every picture. I hope someone could help me out!
Thanks
What about image_file.save("{}_blackandwhite1.png".format(x))?
It can be more specific if you elaborate on how do you want your originalname to be

Issue saving JPG images from binary data in python

I am having issues with a function that creates JPG images given a binary string. The program saves two images in quick succession, the first is ~300kb and the second is a cropped version of the same image, around ~30kb
The first (larger) image always saves correctly, however the second image sometimes (Maybe 1 in 4) gets cut off half way, with the lower part of the image being flat grey. Opening the image in notepad++ , it looks like the data just abruptly stops being written
The function that creates the images:
def writeImage(imageData, decoded, imageNumber, config):
if imageNumber == 1:
imageSavePath = image1name
elif imageNumber == 2:
imageSavePath = image2name
print(imageSavePath)
file = open(imageSavePath, 'w+b')
file.write(imageData)
file.close
https://i.imgur.com/T4WSOEX.jpg
This is an example of how the images turn out, the amount that is cut off varies image to image
It sounds like your file isn't being flushed before closing. This should happen automatically when you close it. Your code appears to be missing the () for the close call, e.g. it should be
file.close()
The more pythonic way of handling the file object though is to use a with statement as a context manager. So the code would look like this
def writeImage(imageData, decoded, imageNumber, config):
if imageNumber == 1:
imageSavePath = image1name
elif imageNumber == 2:
imageSavePath = image2name
print(imageSavePath)
with open(imageSavePath, 'w+b') as file:
file.write(imageData)
The file will automatically be closed when you are done with executing the statements nested in the with. This ensures you don't forget to close it and leak the file descriptor.

Python/Pygame Converting a .jpg to a string and back to a .jpg: Corruption Issue

I'm making a program in Python using Pygame that will load an image to the screen, open the raw data (as in, the characters you would see if you opened the jpg as a text file), throw some random characters in with the data, and then resave it as a jpg to load into pygame again. This results in a cool looking glitch effect.
I am not having any problems with the desired glitches, but I was finding that despite what kind of random character was placed where, for certain images every time the image went through my glitch function I ended up with a grey bar on the bottom of the image. I simplified my function so that all it did was load the image, open the image as a read binary (even though I'm on a mac), save a string of the raw data, write a new file based on this string and then load that file. The image was not purposefully glitched in any way, and the data was supposedly untouched but I still encountered this grey bar.
Here is the relevant code:
def initializeScreen(x, y):
pygame.display.set_mode((x,y))
return pygame.display.get_surface()
def importImage(fileName):
imgText = open(fileName, 'rb')
imgTextStr = imgText.read()
imgText.close()
return imgTextStr
screenSurf = initializeScreen(800,600)
textOfImg = importImage('/Users/Amoeba/Desktop/GlitchDriving/Clouds.jpg')
newFile = open('/Users/Amoeba/Desktop/GlitchDriving/tempGlitchFile.jpg', 'wb')
newFile.write(textOfImg)
newimgSurf = pygame.image.load('/Users/Amoeba/Desktop/GlitchDriving/tempGlitchFile.jpg')
screenSurf.blit(newimgSurf, (0,0))
pygame.display.flip()
Here is an example of one of the images before and after passing through my function:
It is worth noting that the size of the grey bar depends on the picture. Some pictures even pass through my function visibly unchanged, as they should be. Also, if I open the new version of the jpg written by my program with image viewing software like preview, the grey bar does not appear. My suspicion is that it is a quirk of the pygame image load function or that there is some strange character (or possibly white space) that is being dropped in my conversion from jpg to string or vice-versa. I did compare two of the text files (one with grey bar and one without) and found no difference while using an online "difference finder".
This is my first post here, but I've lurked for answers dozens of times. Any help is greatly appreciated.
You never close the file object you create with open, so probably not all data gets written back (flushed) to your new file.
Either close the file object before trying to read the file again, or better start using the with statement (which will close the file for you) whenever you deal with files:
def importImage(fileName):
with open(fileName, 'rb') as imgText:
return imgText.read()
screenSurf = initializeScreen(800,600)
textOfImg = importImage(r'path/to/file')
with open(r'path/to/otherfile', 'wb') as newFile:
newFile.write(textOfImg)
newimgSurf = pygame.image.load(r'path/to/otherfile')
screenSurf.blit(newimgSurf, (0,0))
pygame.display.flip()

Categories