C
C#4w ago
Joe Black

Hi guys i have a problem with my c# - python code!

I have a code for image recognizing. It works fine in my vs code. Heres a screenshot And this code works fine in visual studio in python solution. But when I try to run it inside my c# code it does not work. My model is loading properl;y and path to my file is fine too. Libraries connects also in proper way. I run this code using pythonnet inside c#. But my code stops on that line "prediction = model.predict(processed_image)" with that error. Mb someone knows how to fix it or have a solution?
No description
No description
No description
No description
9 Replies
canton7
canton74w ago
What's the call stack on that exception? Also please post code as text, not images. See $code. I want to ctrl-f through it to see if there's a write function anywhere, but I can't, because it's an image.
MODiX
MODiX4w ago
To post C# code type the following: ```cs // code here ``` Get an example by typing $codegif in chat For longer snippets, use: https://paste.mod.gg/
Joe Black
Joe BlackOP4w ago
private void analyzeBtn_Click(object sender, EventArgs e) {
if (String.IsNullOrEmpty(this.filePathLb.Text) == true) return;

//python(version) dll path on machine
Runtime.PythonDLL = @"C:\Users\D1mentrrr\AppData\Local\Programs\Python\Python311\python311.dll";
PythonEngine.Initialize();

using (Py.GIL()) {
// Import sys module
dynamic sys = Py.Import("sys");

//current bin/debug directory
sys.path.append(@".");

// Python scrypt
dynamic script = Py.Import("scrypt");
string message = script.ImageAnalyze("D:\\VisualStudio\\PythonApplication1\\12630.png"); // dont look at the path its not used and its just a plug for function

MessageBox.Show(message);
}
}
private void analyzeBtn_Click(object sender, EventArgs e) {
if (String.IsNullOrEmpty(this.filePathLb.Text) == true) return;

//python(version) dll path on machine
Runtime.PythonDLL = @"C:\Users\D1mentrrr\AppData\Local\Programs\Python\Python311\python311.dll";
PythonEngine.Initialize();

using (Py.GIL()) {
// Import sys module
dynamic sys = Py.Import("sys");

//current bin/debug directory
sys.path.append(@".");

// Python scrypt
dynamic script = Py.Import("scrypt");
string message = script.ImageAnalyze("D:\\VisualStudio\\PythonApplication1\\12630.png"); // dont look at the path its not used and its just a plug for function

MessageBox.Show(message);
}
}
Its c# code that needs to get just a string from my python code. I'm using pythonnet here for that. There's python code
//python code
def ImageAnalyze(filePath):
import os
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
model = load_model('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\traffic_classifier.keras', compile = False)
if os.path.exists('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\traffic_classifier.keras') is False:
return "Keras not found"
def preprocess_image(image_path):
try:
image = Image.open(image_path)
image = image.resize((30, 30))
image = np.array(image)

image = np.expand_dims(image, axis=0)
return image
except Exception as e:
print(f"Error processing image: {e}")
return None
processed_image = preprocess_image('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\12630.png')
if os.path.exists('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\12630.png') is False:
return "Phott not found"
if processed_image is not None:
prediction = model.predict(processed_image)
predicted_class = np.argmax(prediction, axis=1)[0]
message = f"Predicted Class: {predicted_class}"
return message
else:
return "Error: Unable to process image"
//python code
def ImageAnalyze(filePath):
import os
from tensorflow.keras.models import load_model
from PIL import Image
import numpy as np
model = load_model('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\traffic_classifier.keras', compile = False)
if os.path.exists('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\traffic_classifier.keras') is False:
return "Keras not found"
def preprocess_image(image_path):
try:
image = Image.open(image_path)
image = image.resize((30, 30))
image = np.array(image)

image = np.expand_dims(image, axis=0)
return image
except Exception as e:
print(f"Error processing image: {e}")
return None
processed_image = preprocess_image('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\12630.png')
if os.path.exists('D:\\VisualStudio\\RoadSignImageAnalyzer\\bin\\Debug\\net8.0-windows\\12630.png') is False:
return "Phott not found"
if processed_image is not None:
prediction = model.predict(processed_image)
predicted_class = np.argmax(prediction, axis=1)[0]
message = f"Predicted Class: {predicted_class}"
return message
else:
return "Error: Unable to process image"
it works well. libraries also imports well(i checked the possibility to return every library version as string from that method so libraries is not a problem. Also filepath is fine and kernel trained model is fine too. This code works in another solution or in vs code jupiter notebook or even from my desctop in cmd/ But when i start it from c# it stops on that line
prediction = model.predict(processed_image)
prediction = model.predict(processed_image)
and then i heave this kind of exception Python.Runtime.PythonException: ''NoneType' object has no attribute 'write''
Joe Black
Joe BlackOP4w ago
also there is my call stack
No description
Joe Black
Joe BlackOP4w ago
and there is exception screenshot
No description
Joe Black
Joe BlackOP4w ago
@canton7
Joe Black
Joe BlackOP4w ago
and there s a trained model and a picture wich i used for recognizing
Joe Black
Joe BlackOP4w ago
Desired output is Predicted class: 35
No description
Joe Black
Joe BlackOP4w ago
Its not necessary because the same code works in just python solution but dont work when i start it in c#. I already had an advice about ctrl+f for .where so it's not the reason for exception
Want results from more Discord servers?
Add your server