Cannot run opencv-python script in node.js : No module named cv2 - python

Using this code to for capturing image and it is running well on spyder-anaconda but I want to integrate with my app which is made on node.js platform but unable to do so.
the beginning of python code is as follows :
//cam_open.py
import cv2
import numpy as np
aarcascade_frontalface_default.xml"
detector=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
cam = cv2.VideoCapture(0)
#------Id=raw_input('enter your id')----
Id=1
path= 'Dataset1'
sampleNum=0
while(True):
ret, img = cam.read();
.
.
.
and code for integrating with node.js is as follows:
(note: I have used this code to run other python scripts and it is running perfect on them but when I include opencv it is giving me errors even though I have added opencv path to my environment variables too)
//index.js
var PythonShell = require('python-shell');
var pyshell = new PythonShell('cam_open.py');
pyshell.on('message', function (message) {
console.log(message);
});
the error I'm getting is as follows:
HIBA#hiba-pc MINGW64 ~/documents/sabah/driver-comp/test
$ node index.js
events.js:137
throw er; // Unhandled 'error' event
^
Error: ImportError: No module named cv2
at PythonShell.parseError (C:\Users\HIBA\documents\sabah\driver-comp\node_modules\p
ython-shell\index.js:184:17)
at terminateIfNeeded (C:\Users\HIBA\documents\sabah\driver-comp\node_modules\python
-shell\index.js:98:28)
at ChildProcess.<anonymous> (C:\Users\HIBA\documents\sabah\driver-comp\node_modules
\python-shell\index.js:89:9)
at ChildProcess.emit (events.js:160:13)
at Process.ChildProcess._handle.onexit (internal/child_process.js:209:12)
----- Python Traceback -----
File "cam_open.py", line 1, in <module>
import cv2
Can anybody here help me get out of this :)

Related

OSError: cannot open resource while using text_to_font module

I am trying to make a quotes generator in Python. You can see my code below:
from quotefancy import get_quote
from text_to_font.transformations import word_to_ascii
a=get_quote(type='text')
print(word_to_ascii(
phrase=a,
font_size=3,
kerning=1,
font_path='~/fonts/somefont.ttf'
))
While running this script I am getting this error:

How to connect Python Selenium with Electron JS App

I'm building a simple automation app that will use Electron JS for good GUI and then Python Selenium to automate the task.
I've just started when I'm trying to run electron JS app it shows that there is no module named as selenium.
Here is my python (demo.py)
import time
import re
from selenium import webdriver
import webbrowser
import sys
from selenium.webdriver.common.keys import Keys
browser = webdriver.Firefox()
browser.get('https://example.com')
userid = browser.find_element_by_id('user')
time.sleep(1)
userpass = browser.find_element_by_id('password')
time.sleep(1)
userid.send_keys('aafasdf#gmail.com')
time.sleep(1)
userpass.send_keys('#jlasdjf#')
time.sleep(1)
userid.send_keys(Keys.RETURN)
userid.clear()
browser.refresh()
time.sleep(5)
print('Hello from Python!')
sys.stdout.flush()
And the goes my index.js file
-
function some(){
var ps = require("python-shell")
var path = require("path")
var options = {
scriptPath : path.join(__dirname,'../seleniumBro/'),
pythonPath : '/usr/local/bin/python3.8'
}
ps.PythonShell.run('../../seleniumBro/demo.py', options, function (err, results) {
if (err) throw err;
// swal(results[0]);
console.log(results[0])
});
}
When I run the app I get this error in console.
index.js:12 Uncaught Error: ModuleNotFoundError: No module named 'selenium'
at PythonShell.parseError (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:258:21)
at terminateIfNeeded (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:141:32)
at ChildProcess.<anonymous> (/Users/rahul/Desktop/justDev/electronBro/hello-world/node_modules/python-shell/index.js:133:13)
at ChildProcess.emit (events.js:223:5)
at Process.ChildProcess._handle.onexit (internal/child_process.js:272:12)
----- Python Traceback -----
File "/Users/rahul/Desktop/justDev/seleniumBro/demo.py", line 3, in <module>
from selenium import webdriver
I'm on MAC OS. And also new to this. Please help.
As per my views. You should go with Node.js as said by pguardio that Selenium is available for node too.

Python scripts not working but Spyder and CMD

I am working with Anaconda-spyder, my scripts are working fine in spyder also I can run it from CMD
but I can not run my scripts with my Nodejs app
Nodejs
const express = require('express');
const router = express.Router();
const {PythonShell} = require("python-shell");
router.get('/hi', (req, res, next)=> {
console.log("here");
PythonShell.run('pyt//home.py', {
args: ['infoo']
}, function (err, results) {
console.log("here2");
if(results)
{ console.log(results);}
if(err)
{ console.log(err);}
});
});
module.exports = router;
In python code, used libraries
import os
import sys
import tweepy,codecs
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import nltk
from textblob import Word
import six
import numpy as np
import pandas as pd
from os import path
from PIL import Image
from wordcloud import WordCloud, STOPWORDS, ImageColorGenerator
from nltk.corpus import stopwords
from matplotlib.backends.backend_pdf import PdfPages
import time
And getting the argv parameter in home.py with
if __name__ == "__main__":
twt = sys.argv[1]
print("hi python")
When I run server, get the route with postman. console says
[nodemon] watching path(s): *.*
[nodemon] watching extensions: js,mjs,json
[nodemon] starting `node ./bin/www`
here
here2
{ Error: ModuleNotFoundError: No module named 'pandas'
at PythonShell.parseError (C:\Users\username\Desktop\NodejsBitirme\node_modules\python-shell\index.js:258:21)
at terminateIfNeeded (C:\Users\username\Desktop\NodejsBitirme\node_modules\python-shell\index.js:141:32)
at ChildProcess.<anonymous> (C:\Users\username\Desktop\NodejsBitirme\node_modules\python-shell\index.js:133:13)
at ChildProcess.emit (events.js:198:13)
at Process.ChildProcess._handle.onexit (internal/child_process.js:248:12)
----- Python Traceback -----
File "pyt\home.py", line 9, in <module>
Seems like installed libs problem. It work from cmd.
In the same folder
python home.py "hello"
It works

Error while opening the image in opencv and python

I am trying to start with basics of opencv with python but when i executed the below code :
import cv2
import numpy as np
img = cv2.imread('bg.jpg',cv2.IMREAD_GRAYSCALE)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
But i am getting this error:-
Traceback (most recent call last):
File "F:\OpenCV Programs\OpenCV1.py", line 7, in <module>
cv2.imshow('image',img)
error: C:\build\master_winpack-bindings-win32-vc14-
static\opencv\modules\highgui\src\window.cpp:331: error: (-215) size.width>0
&& size.height>0 in function cv::imshow
Plz help me out thank you..!
The code you posted works, if there is an image called bg.jpg within the same directory where you are running the code.
Anyway, you could try to reference the full path to the image:
import os
img_path = os.path.join(os.getcwd(), 'bg.jpg')
img = cv2.imread(img_path,cv2.IMREAD_GRAYSCALE)
The image you attempt to load does not exist.
As you cannot display a non-existing image you get an error messsage for trying.
You'll most likely messed up the path. Maybe use an absolute path to the image.

Python script just printing out blank page

I am using xampp and I am able to run simple python script on it so xampp is setup fine for python. I am trying to use pillow.
I have installed anaconda and did following in terminal
conda install pillow
If I run test.py below in terminal, it works fine. It prints format, size, mode.
But if I try it from web browser I'm getting blank page.
Here is test.py
#!/Library/Frameworks/anaconda/bin/python
print("Content-Type: text/html")
print()
print("<html><head><title>Python</title></head><body>")
from PIL import Image, ImageFilter
original = Image.open("Lenna.png")
print("<h5>The size of the Image is: </h5>")
print("<h2>size " + original.format, original.size, original.mode + "</h2>")
if I use cgitb.enable() I get following error
A problem occurred in a Python script. Here is the sequence of function calls leading up to the error, in the order they occurred.
/Applications/XAMPP/xamppfiles/cgi-bin/test7.py in ()
8 print("<html><head><title>Python</title></head><body>");
9 print("<h5>The size of the Image is: </h5>");
=> 10 from PIL import Image
11 original = Image.open("Lenna.png");
12 width, height = original.size;
PIL undefined, Image undefined
/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/Image.py in ()
61 # Also note that Image.core is not a publicly documented interface,
62 # and should be considered private and subject to change.
=> 63 from PIL import _imaging as core
64 if PILLOW_VERSION != getattr(core, 'PILLOW_VERSION', None):
65 raise ImportError("The _imaging extension was built for another "
PIL undefined, _imaging undefined, core = <PIL.Image._imaging_not_installed object>
ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so, 2): Library not loaded: #loader_path/.dylibs/libtiff.5.dylib Referenced from: /Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so Reason: Incompatible library version: _imaging.so requires version 8.0.0 or later, but libtiff.5.dylib provides version 6.0.0
args = ('dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0',)
msg = 'dlopen(/Library/Frameworks/Python.framework/Vers...later, but libtiff.5.dylib provides version 6.0.0'
name = '_imaging'
path = '/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-packages/PIL/_imaging.so'
with_traceback = <built-in method with_traceback of ImportError object>
Kind of an anti-answer, but unless you are doing it this way for academic reasons, you should try one of the more standard frameworks:
Flask
bottle.py
The two frameworks I listed above are examples of minimalist frameworks that do not get in your way. They take care of running your app and setting up routes. The minimum to use Flask is this:
from flask import Flask
from PIL import Image, ImageFilter
app = Flask(__name__)
#app.route("/")
def myview():
original = Image.open("Lenna.png")
return """
<html><head><title>Python</title></head>
<body>
<h5>The size of the Image is: </h5>
<h2>size {format}, {size}, {mode}</h2>
</body></html>""".format(
format=original.format,
size=original.size,
mode=original.mode)
app.run()
Next, if you want to make your app available, you only need to setup a reverse proxy in XAMPP (easy-peasy). I highly suggest using Flask; it comes with an awesome in-page debugger, courtesy of its sister project Werkzeug (lit. "toolbox").
Werkzeug debugger:

Categories

Resources