TypeError ‘NoneType’ object is not subscriptable Error Flask

  Kiến thức lập trình
``<kbd>@app.route('/upload', methods=['GET', 'POST'])
def upload(): 
    chart_image = None
    if request.method == 'POST':
        if 'img_file' in request.files:
            file = request.files['img_file']
            if file.filename != '':
                filename = secure_filename(file.filename)
                file_path = os.path.join(UPLOAD_FOLDER, filename)
                file.save(file_path)
                img = predictor(file_path)  
                img_cut = nn(file_path)
                if img is not None:
                 color_detection_chart = color_detection12(img_cut, n_colors=3, show_chart=True, output_chart='static/color_chart.png')
                 chart_image = 'static/color_chart.png'
                else:
                    print("PROBLEM")
                    pass`

    return render_template('upload.html', chart_image=chart_image)
`def predictor(img_file):
    img = cv2.imread(img_file)
    resize = cv2.resize(img, (64, 64))
    # resize = np.expand_dims(resize, axis=0)

    img_fin = np.reshape(resize, [1, 64, 64, 3])
    json_file = open('model/binaryfas10.json', 'r')
    loaded_model_json = json_file.read()
    json_file.close()

    loaded_model = model_from_json(loaded_model_json)
    loaded_model.load_weights("model/binaryfashion.h5")
    # print("Loaded model from disk")

    prediction = loaded_model.predict(img_fin)

    prediction = np.squeeze(prediction, axis=1)
    predict = np.squeeze(prediction, axis=0)
    return int(predict)
`

"""Neural Network Decoding"""
""" The coordinates are created and trained"""
"""-----------------"""
image_width = 300
image_height = 500


def path_file(file):
    return str(file)




import cv2
import numpy as np



def color_detection12(img, n_colors, show_chart=False, output_chart=None):
    # RGB formatına dönüştürme
   # img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
   # print(img.shape)
    # Alfa kanalını kaldırma
    img = img[:, :, 2]  

    clf = KMeans(n_clusters=n_colors)
    colors = clf.fit_predict(img.reshape(-1, 3))
    counts = Counter(colors)
    center_colors = clf.cluster_centers_
    ordered_colors = [center_colors[i] for i in range(n_colors)]
    hex_colors = ['#%02x%02x%02x' % tuple(map(int, color)) for color in ordered_colors]

    color_category = dict(zip(hex_colors, counts.values()))

    if show_chart:
        plt.figure(figsize=[10, 10])
        plt.pie(color_category.values(), labels=color_category.keys(), colors=color_category.keys())
        plt.savefig(output_chart)

    return color_category




def nn(img_file):
    predict = predictor(img_file)
    file = path_file("annotation.csv")
    reader = pd.read_csv(file)
    #print(predict)

    img = cv2.imread(img_file)
    img = cv2.resize(img, (image_width, image_height))
    # seg = img(img, reader.x1[predict], reader.y1[predict], reader.x2[predict], reader.y2[predict], reader.i[predict])

    mask = np.zeros(img.shape[:2], np.uint8)

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

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

    rect = (reader.x1[predict], reader.y1[predict], reader.x2[predict], reader.y2[predict])
    cv2.grabCut(img, mask, rect, bgdModel, fgdModel, reader.i[predict], cv2.GC_INIT_WITH_RECT)
    mask2 = np.where((mask == 2) | (mask == 0), 0, 1).astype('uint8')

    img_cut = img*mask2[:, :, np.newaxis]
    

    img_array = cv2.imread('examples/grabcut_dress2.png')
    
#     cv2.imshow("name",img_array)
    #img_array = cv2.cvtColor(img_array, cv2.COLOR_BGR2RGB)
#     cv2.waitKey(0)
    color_detection12(img_array, n_colors=3, show_chart=True, output_chart=output_chart)
    # find_dominant_color_quantization(img_array)
#nn(file_path)


if __name__ == '__main__':
    app.run(debug=True, host='127.0.0.1',port=5000)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dosya Yükle</title>
</head>
<body>
    <h1>Dosya Yükle</h1>
    <form action="/upload" method="POST" enctype="multipart/form-data">
        <input type="file" name="img_file" accept="image/*">
        <input type="submit" value="Upload" onclick="upload()">
        <button type="submit" value="Upload" onclick="upload()">UPLOAD</button>
        <button></button>
    </form>
   
    <h2>Color Chart</h2>
    <img src="{{ url_for('static', filename=chart_image) }}" alt="Color Chart">

</body>
</html>`

When I pressed the upload button on the image I uploaded, I made a graph cut with the nn function and showed the dominant color. I wrote the code. I want to integrate it with Flask for web, but when I wanted to show a chart image on the upload page, fashion.py”, line 109, in upload
color_detection_chart = color_detection12(img_cut, n_colors=3, show_chart=True, output_chart=’static/color_chart.png’)
fashion.py”, line 160, in color_detection12
img = img[:, :, 2]
TypeError: ‘NoneType’ object is not subscriptable

New contributor

Merve CELİK is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT