Error: The indentation does not match any outer level of indentation (I am using Sublime Text)

Every time I try to run this script, an error pops up: IndentationError: unindent does not match any outer indentation level. I've attempted to troubleshoot in various code editors such as Sublime and Visual Studio Code, but the issue persists. This is a problem I have never encountered before. The code:

import cv2
import numpy as np

video = cv2.VideoCapture(0)

while True:

    check, frame = video.read()

    if not check:
        print("Camera doesn't work")
        break

    pressed = cv2.waitKey(1)
    if pressed == ord("q"):
        break


    blur = cv2.GaussianBlur(frame, (21, 21), 0)
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
    lower = [18, 50, 50]
    upper = [35, 255, 255]
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")
    mask = cv2.inRange(hsv, lower, upper)

    output = cv2.bitwise_and(frame,hsv, mask=mask)
    cv2.imshow("Frame", output)

video.release()

cv2.DestroyAllWindows()

Edit: It seems there is a missing closing tag at the mask line and also a missing line (import numpy as np). Although these mistakes occurred while copying the code, the error remains consistent when trying to execute it.

Answer №1

Python's unique syntax sets it apart from most other programming languages. Instead of relying on brackets or statements to group code, Python uses indentation to indicate block structure. This means that code blocks must be indented consistently, with either tabs or spaces (not a mix of both).

It is recommended to choose one method and stick with it throughout your codebase. Personally, I advocate for using spaces over tabs in Python.

Answer №2

The issue on line 24 is due to a missing closing bracket

mask = cv2.inRange(hsv, lower, upper

Answer №3

There seems to be a small error in the code snippet you provided, specifically with the indentation. The only issue found is a missing left parenthesis in this line:

    mask = cv2.inRange(hsv, lower, upper

Additionally, it appears that you forgot to import the np module. To correct this, simply add the following line at the beginning of your code:

 import numpy as np

Once these adjustments are made, your code should run without any problems.

Answer №4

Successfully implemented this Python 3 code snippet!

import cv2
import numpy as np

video = cv2.VideoCapture(0)

while True:

    check, frame = video.read()

    if not check:
        print("Camera is not functioning properly")
        break

    pressed = cv2.waitKey(1)
    if pressed == ord("q"):
        break

    blur = cv2.GaussianBlur(frame, (21, 21), 0)
    hsv = cv2.cvtColor(blur, cv2.COLOR_BGR2HSV)
    lower = [18, 50, 50]
    upper = [35, 255, 255]
    lower = np.array(lower, dtype="uint8")
    upper = np.array(upper, dtype="uint8")
    mask = cv2.inRange(hsv, lower, upper) # closing the command 

    output = cv2.bitwise_and(frame, hsv, mask=mask)
    cv2.imshow("Frame", output)

video.release()

cv2.destroyAllWindows() # make sure to use lowercase 'd' for destroy.

No indentation issues encountered. I recommend utilizing a debugger tool like PyCharm for troubleshooting any unforeseen errors.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Asking for an API request in python that necessitates an oauth token

As I work on a program to send data to a specific URL and receive a response, I encountered an issue while using Python. The problem arose when trying to include a token in the request as required by Postman, resulting in a [401] response. The main obstac ...

I am struggling to comprehend the einsum calculation

As I attempt to migrate code from Python to R, I must admit that my knowledge of Python is far less compared to R. I am facing a challenge while trying to understand a complex einsum command in order to translate it. Referring back to an answer in a previ ...

Python3 requires a bytes-like object to be encoded in Base64

Here is the code snippet: _cmd = "|| echo " + base64.b64encode(args.cmd) + "|base64 -d|bash" p.update({"form_284": _cmd}) The error encountered is as follows: Traceback (most recent call last): File "openemr_rce.py& ...

Troubleshooting Problems with Mapbox API Key

Once pydeck was installed, I configured the MAPBOX_ACCESS_TOKEN: export MAPBOX_ACCESS_TOKEN=pk.eyJ1Ijoibmlrb2dhbXVsaxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxlRyMZPMp4ASJ0yyA However, when attempting to display a map in a jupyter notebook, I ...

Python function to validate input while preserving original values

While developing a tax calculator application, I encountered an issue with the validation of input tax codes. It appears that the program rejects invalid tax codes initially, but then proceeds to hold onto the original inputs and iterates through them in r ...

cryptic SQLite3 error

I have created a Python database using SQLite3 and I am encountering an error when trying to add data. The error message states, You did not supply a value for binding 1. I have previously made the same type of database with different values and did not fa ...

Issue with dropdown menu in selenium is that it is unable to switch to the second option

Currently, I am in the process of web scraping on a specific page . When Selenium initiates the initial loading of the page, I encounter a requirement to select both the state and city. To address this, I attempted using the .click method. select_state = d ...

Retrieve specific elements from a loop

I need help with a Python for loop that prints values ranging from 3 to 42.5. However, I am looking to store only the values between 1 and 8 in a variable. with requests.Session() as s: r = s.get(url, headers=headers) soup = BeautifulSoup(r.text, &apos ...

Display contents from a JSON file

I need to extract unique locality values from a JSON file in Python, but my current code is only printing the first few entries and not iterating through all 538 elements. Here's what I have: import pandas as pd import json with open('data.json ...

What is the best way to incorporate a function into a while loop in order to achieve my desired result?

import random u = int(input("Enter the security parameter")) half = int(u/2) def Prime_Check(n): isprime = True for i in range(2,int(n/2)): if n % i == 0: print("is not prime") isprime = False ...

Error: SSLError encountered due to a MaxRetryError while attempting to connect to `huggingface.co` on port 443

Can anyone help me troubleshoot an issue I'm having with the SentenceTransformers? I followed the instructions on this page, but when I run the code below, I encounter an error that I can't seem to resolve: import torch from sentence_transformers ...

Error: The __init__() function is lacking the required argument 'timeout.'

Despite initializing the super class constructor, I am encountering an error while trying to run some basic test cases for a simple project. Here is the code snippet: home.py class home(Pages): user = (By.NAME, "user-name") utxt = " ...

Retrieving and saving images from Azure Blob Storage

I need help with exporting matplotlib plots from Databricks to Blob Storage. Currently, I am using the following code: plt.savefig('/dbfs/my_plot.png') dbutils.fs.cp('dbfs:my_plot.jpg', blob_container) However, the issue arises when I ...

Is multiprocessing the answer?

Imagine having a function that retrieves a large amount of data from a device each time it is called. The goal is to store this data in a memory buffer and when the buffer reaches a certain size, another function should come into play to process it. Howeve ...

Configuring the primary language on AliExpress while utilizing Playwright

I've been experimenting with the Playwright Async API in order to extract data and create tests. Here is an example of how I'm using it: from playwright.async_api import async_playwright async def aliexpress(browser_url, product_url): async w ...

The "dense3" layer is throwing an error due to incompatible input. It requires a minimum of 2 dimensions, but the input provided only has 1 dimension. The full shape of the input is (4096,)

Having recently delved into the realms of keras and machine learning, I am experiencing some issues with my code that I believe stem from my model. My objective is to train a model using a CSV file where each row represents a flattened image, essentially m ...

Python is the way to go for clicking on a link

I have a piece of HTML and I am in need of a Python script using selenium to click on the element "Odhlásit se". <div class="no-top-bar-right"> <ul class="vertical medium-horizontal menu" dat ...

Scraping the web with a webdriver using a for loop

My task involves scraping data from this specific website: this link. The main challenge is to extract content located in the right box of each page until the last item is reached. This means that clicking on the "<이전글" (previous item) or "다음 ...

choose checkbox option in python

Suppose you have an XML document structured as follows: <!-- Location --> <w:t>Location:</w:t> <w:t>Home:</w:t> <w:t>Extension:</w:t> <w:t>Hajvali –Prishtina</w:t> <w:t>Street. "Martyrs of Goll ...

Python Script for Conducting a Google Search

Looking to develop a Python script that can take a user-entered question and fetch the answer using Google Custom Search API, Bing, or another search API. When attempting to use the Google Custom Search API, I encountered the following script: <script& ...