简体   繁体   中英

Flask error: The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again

I am a newbie to Flask and I am creating my Flask project titled Image Processing using OpenCV. In this project a user can perform image processing by uploading an image and it will be transformed using the corresponding OpenCV function in the backend. The home page looks like this home page

It consists of clickable cards depicting various operations which on clicking will direct to the corresponding on page.But on clicking the cards I am getting the error The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.Please help me with this

Here is the project structure project structure

Here is the routes.py code

    from flask import Flask,render_template,url_for
import os
from app import app
from app.forms import PhotoForm
import cv2
import numpy as np

@app.route('/')
@app.route('/options',methods=['GET','POST'])
def options():
    return render_template('options.html')

UPLOAD_FOLDER = './upload'
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/scaling',methods=['GET','POST'])
def scaling():
    #f=request.files['file']
    #f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    #full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    #img = cv2.imread(full_filename)
    #res = cv2.resize(img,(2*width, 2*height))
    return render_template('scaling.html')

@app.route('/rotation')
def rotation():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)
    rows,cols = img.shape
    M = cv2.getRotationMatrix2D((cols/2,rows/2),90,1)
    dst = cv2.warpAffine(img,M,(cols,rows))
    return render_template('rotation.html')

@app.route('/grayconversion')
def grayconversion():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)
    gray_img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
    render_template('grayconverison.html')

@app.route('/facedetection')
def facedetection():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)
    for (x,y,w,h) in faces:
       res_img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
       roi_gray = gray[y:y+h, x:x+w]
       roi_color = img[y:y+h, x:x+w]
       eyes = eye_cascade.detectMultiScale(roi_gray)
       for (ex,ey,ew,eh) in eyes:
           cv2.rectangle(roi_color,(ex,ey),(ex+ew,ey+eh),(0,255,0),2)    
    render_template('facedetction.html')

@app.route('/edgedetection')           
def edgedetection():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename) 
    edges = cv2.Canny(img,100,200)
    render_template('edgedetection.html')

@app.route('/cornerdetection')
def cornerdetection():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    gray = np.float32(gray)
    dst = cv2.cornerHarris(gray,2,3,0.04)

#result is dilated for marking the corners, not important
    dst = cv2.dilate(dst,None)

# Threshold for an optimal value, it may vary depending on the image.
    img[dst>0.01*dst.max()]=[0,0,255]
    render_template('cornerdetection.html')


@app.route('/linedetection')
def linedetection():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename) 
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    edges = cv2.Canny(gray,50,150,apertureSize = 3)

    lines = cv2.HoughLines(edges,1,np.pi/180,200)
    for rho,theta in lines[0]:
       a = np.cos(theta)
       b = np.sin(theta)
       x0 = a*rho
       y0 = b*rho
       x1 = int(x0 + 1000*(-b))
       y1 = int(y0 + 1000*(a))
       x2 = int(x0 - 1000*(-b))
       y2 = int(y0 - 1000*(a))

    cv2.line(img,(x1,y1),(x2,y2),(0,0,255),2)     
    cv2.imwrite('linedetection.jpg',img)
    render_template('linedetection.html')     

@app.route('/circledetection')
def circledetection():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)   
    img = cv2.medianBlur(img,5)
    cimg = cv2.cvtColor(img,cv2.COLOR_GRAY2BGR)

    circles = cv2.HoughCircles(img,cv2.HOUGH_GRADIENT,1,20,
                            param1=50,param2=30,minRadius=0,maxRadius=0)

    circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
    # draw the outer circle
        cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
        cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)
    render_template('circledetection.html')

@app.route('/imagesegmentation')
def imagesegmentation():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)   
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
    ret, thresh = cv2.threshold(gray,0,255,cv2.THRESH_BINARY_INV+cv2.THRESH_OTSU)
    # noise removal
    kernel = np.ones((3,3),np.uint8)
    opening = cv2.morphologyEx(thresh,cv2.MORPH_OPEN,kernel, iterations = 2)

# sure background area
    sure_bg = cv2.dilate(opening,kernel,iterations=3)

# Finding sure foreground area
    dist_transform = cv2.distanceTransform(opening,cv2.DIST_L2,5)
    ret, sure_fg = cv2.threshold(dist_transform,0.7*dist_transform.max(),255,0)

# Finding unknown region
    sure_fg = np.uint8(sure_fg)
    unknown = cv2.subtract(sure_bg,sure_fg)

    # Marker labelling
    ret, markers = cv2.connectedComponents(sure_fg)

# Add one to all labels so that sure background is not 0, but 1
    markers = markers+1

# Now, mark the region of unknown with zero
    markers[unknown==255] = 0
    markers = cv2.watershed(img,markers)
    img[markers == -1] = [255,0,0]
    render_template('imagesegmentation.html')

@app.route('/erosion')
def erosion():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)   
    kernel = np.ones((5,5),np.uint8)
    erosion = cv2.erode(img,kernel,iterations = 1)
    render_template('erosion.html')

@app.route('/dilation')
def dilation():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)  
    kernel = np.ones((5,5),np.float32)/25
    dilate = cv2.dilate(img,kernel,iterations = 1)
    render_template('dilation.html')

@app.route('/blurring')
def blurring():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)   
    kernel = np.ones((5,5),np.float32)/25
    dst = cv2.filter2D(img,-1,kernel)
    render_template('blurring.html')

@app.route('/foregroundextraction')
def foregroundextraction():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)
    mask = np.zeros(img.shape[:2],np.uint8)

    bgdModel = np.zeros((1,65),np.float64)
    fgdModel = np.zeros((1,65),np.float64)

    rect = (50,50,450,290)
    cv2.grabCut(img,mask,rect,bgdModel,fgdModel,5,cv2.GC_INIT_WITH_RECT)

    mask2 = np.where((mask==2)|(mask==0),0,1).astype('uint8')
    res = img*mask2[:,:,np.newaxis]   
    render_template('foregroundextraction')

@app.route('/laplacianderivative')
def laplacianderivative():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)  
    laplacian = cv2.Laplacian(img,cv2.CV_64F)
    render_template('laplacianderivative.html')


@app.route('/sobelderivative')
def sobelderivative():
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)   
    sobelx = cv2.Sobel(img,cv2.CV_64F,1,0,ksize=5)
    sobely = cv2.Sobel(img,cv2.CV_64F,0,1,ksize=5)
    render_template('sobelderivative.html')

@app.route('/masking')
def masking(): 
    f=request.files['file']
    f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
    full_filename = os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
    img = cv2.imread(full_filename)                                  

if __name__== "__main__":
    app.run(debug=True)

Here is the code of one of the html pages to which the cards will direct to

<!DOCTYPE html>
<html lang = "en">
<head>
    <meta charset = "UTF-8">
    <meta name = "viewport" content="width=device-width, initial-scale=1.0,shrink-to-fit=no">
    <meta name = "content" author = "Rigved Alankar">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
    <link rel = "stylesheet" type = "text/css" href = "{{url_for('static',filename='styles/style.css')}}">
    <title>Scaling</title>
</head>
<body>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
    <nav class="navbar navbar-expand-sm bg-dark navbar-dark justify-content-center">
        <a class="navbar-brand" href="#">Image Processing using OpenCV</a>
        <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
          <span class="navbar-toggler-icon"></span>
        </button>
    </nav>
    <br>
    <br>
    <div class="container">
        <div class="row">
          <div class="col-12">
              <p> Please enter the image </p> 
          </div>
        </div>  
        <form method = "POST" action="/scaling" enctype="multipart/form-data" >
              <div class="form-group">
                  <input type="file" class="form-control-file" id="exampleFormControlFile1">
              </div>
        </form> 
    </div>
    <form method='POST' action='http://localhost:5000/'>
        <div class="form-group">
            <label for="label2">Enter the amount of scaling in the x direction</label>
            <input type = "number" class = 'form-control'> 
        </div>
        <div class="form-group">
            <label for="label2">Enter the amount of scaling in the y direction</label>
            <input type = "number" class = 'form-control'> 
        </div>
    </form>
</body>
</html>

Help will be highly appreciated

You must add an if statement for method='POST' as below:

@app.route('/scaling',methods=['GET','POST'])
def scaling():
    if method==['POST']:
        #f=request.files['file']
        #f.save(os.path.join(app.config['UPLOAD_FOLDER'], f.filename))
        #full_filename = 
        os.path.join(app.config['UPLOAD_FOLDER'],f.filename)
        #img = cv2.imread(full_filename)
        #res = cv2.resize(img,(2*width, 2*height))
        return render_template('scaling.html')

The same for all other routes that receive data from forms. Alternatively, you can declare 'POST' as the only method, so that it will not need an if statement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question FLASK - The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again python flask URL error: 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' Flask app - Error 404, The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again Flask - 404 Not found : The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again Flask: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again Flask: Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again Python Flask API : The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again Why am I getting "The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again" The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. 404
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM