python – Multi-core OpenCV denoising

I have ~40,000 JPEG images from the Kaggle melanoma classification competition. I created the following functions to denoise the images:

# Denoising functions
def denoise_single_image(img_path):
    img = cv2.imread(f'../data/jpeg/{img_path}')
    dst = cv2.fastNlMeansDenoising(img, 10,10,7,21)
    cv2.imwrite(f'../processed_data/jpeg/{img_path}', dst)
    print(f'{img_path} denoised.')

def denoise(data):
    img_list = os.listdir(f'../data/jpeg/{data}')
    with concurrent.futures.ProcessPoolExecutor() as executor:
        tqdm.tqdm(, (f'{data}/{img_path}' for img_path in img_list)))

The denoise function uses concurrent.futures to map the denoise_single_image() function over the full list of images.

ProcessPoolExecutor() was used based on the assumption of denoising as a CPU-heavy task, rather than an I/O-intensitve task.

As it stands now, this function takes hours to run. With a CUDA-configured Nvidia GPU and 6 GB VRAM, I’d like to optimize this further.

Is there any way to improve the speed of this function?

Multi-core processing documentation
OpenCV documentation

python – Write in several frames of a video in OpenCV

I have a video which is almost 60sec and I want to apply different video processing techniques in different frames.
I am trying to select different frames, but I am getting a syntax error. THis is what I have written so far.

Function that selects different frames:

def between(cap, lower: int, upper: int):
return lower <= int(cap.get(cv.CAP_PROP_POS_FRAMES)) < upper

And after this I want to select different frames and apply a different technique. For instance below in the first 90 frames I turn then into grayscale and from frame 91 to 150, I want to write some text, but in the second selection of frames, I am getting a syntax error.

`while cap.isOpened():
   ret, frame =
      if not ret:
      print("Can't receive frame (stream end?). Exiting ...")
if between(cap, 0, 90):
          frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)
          frame = cv.cvtColor(frame, cv.COLOR_GRAY2BGR)  
if between(cap, 90, 150)           
# Our operations on the frame come here
          font = cv.FONT_HERSHEY_SIMPLEX 
            'TEXT ON VIDEO',  
            (50, 50),  
            font, 1,  
            (0, 255, 255),  
   # write the flipped frame
cv.imshow('frame', frame)
if cv.waitKey(1) == ord('q'):


Any idea on how I can structure my code to continuously select the next frames.

computer vision – Problem with superpixel segmentation (opencv in python) – holes in contours of the segmentation mask

I am trying superpixel segmentation with OpenCV in Python. I have tried implementing LSC, SLIC and SEEDS algorithms in order to segment cell nuclei, however, so far only SEED algorithm works. Countours or edges in segmentation masks created via .getLabelContourMask() method contained holes for both LSC and SLIC algorithms, which led to flooding of the whole (LSC) or large portion (SLIC) of the mask when using floodfill() method Only SEEDS worked as expected – no apparent openings in contours of the mask, thus only areas around seedpoints flooded after using floodfill() method. Anyone had the same experience? Any idea why this might be the case? Any help appreciated.

Test Code for LSC:

lsc = cv2.ximgproc.createSuperpixelLSC(image, region_size=25, ratio=0.1)
lsc_mask= lsc.getLabelContourMask() #holes visible when zooming in

x, y = lsc_mask.shape
m = np.zeros((x+2, y+2),dtype=np.uint8)

for point in coordinates:
    retval, image, mask, rect = cv2.floodFill(image=lsc_mask, mask=m, seedPoint=point, newVal=(255,255,255), loDiff=0, upDiff=0) 

cv2.imwrite("mask.tif", mask*255) #almost whole mask white
cv2.imwrite("image.tif", image)

python 3.x – Como abrir uma lista de imagens com OpenCV?

Estou tentando abrir imagens e mostrar elas em tela de um diretório chamado ‘Photos’ com várias imagens .jpg, porém quando a janelas abrem elas simplesmente não carregam as imagens e o interpretador não retorna nenhum erro, ele apenas para de funcionar.

import cv2 as cv
from os import listdir, path
import time

path = path.dirname(path.realpath(__file__)) + "Photos"  #Traz o caminho do diretorio atual
files = (f for f in listdir(path))  #Armazena o nome dos arquivos numa lista
print(files) #('cat.jpg', 'cats 2.jpg', 'cats.jpg')

for file in files:
  img = cv.imread(f'Photos/{file}')
  cv.imshow(f"{file}", img)


*Nenhuma dessas imagens ocupa muito espaço (a maior só tem apenas 312kbs)

Tela que deveria mostrar a foto:

c++ – Using OpenCV (with libjpeg) and libjpeg-turbo along each other not working

I am using OpenCV with libjpeg on one side and libjpeg-turbo on the other side. So, libjpeg-turbo is not part of the OpenCV but separate library. I linked agains both libraries in my CMake.

What’s the problem?

OpenCV imdecode function works in case of PNG images but it is not working in case of JPEG images:

cv::Mat img = cv::imread( path );
img.empty(); // returns true

The path is correct one and, when libjpeg-turbo is not linked, everything works well.

Does anyone know what could be the problem? Since I am using Conan OpenCV and libjpeg-turbo packages I cannot make OpenCV to integrate libjpeg-turbo instead of libjpeg.

Convertir una imagen de RGB a YCbCr con Opencv y AndroidStudio

Alguien me podría decir como convertir esto a android, ese codigo esta en python

img = cv2.imread('img1.jpg')
imgYCC = cv2.cvtColor(img,cv2.COLOR_BGR2YCR_CB)

opencv – python modules fail to import

About 2 weeks ago i started opencv python course on youtube, it all worked just fine, but when two days ago I tried to continue learning (In meantime I tried to make disord bot and module worked normally, also there was windows update), python code which used to work stopped doing that. I tried different python versions and reinstalling modules with no result. I deleted all (3) python versions and downloaded latest 3.9.0 version, i reinstalled all modules (I can’t install module now) and it is still not working. I really don’t know what I should do next. Maybe someone had this problem too or knows what to do?

O meu código de screenshot (OpenCv e Pillow) funciona mas gera infinitas janelas em Python

Fiz um código de screenshot com opencv e pillow no Python, porém não funciona.

while True:

cv2.imshow('Python Window', img)

if cv2.waitKey(25) & 0xFF == ord('q'):

O meu código acima funciona, mas gera infinitas janelas do opencv. Alguém sabe resolver este problema?
Já tentei reformular todo o código mas funciona

I am building a captcha generating and checking system with (python + tkinter + Opencv), I am unable to change the image when it is regenerated



from Tkinter import *
import Tkinter.messagebox
from captcha.image import ImageCaptcha
import string
import random
import os
from PIL import ImageTk,Image
import cv2

# global variables

image_captcha = ""
isClicked = False

generate function –

def generate_captcha():
    data_set = list(string.ascii_letters+string.digits)
    s = ""
    for i in range(6):
        a = random.choice(data_set)
        s = s+a

    global image_captcha
    image_captcha = s
    return s

generate image captcha

def generate_image_captcha():

generate the first image

def generate_first_image():
    img = ImageCaptcha()

    s = generate_captcha()

    value = img.generate(s)

get image

def get_image():
    return image_captcha

checking entered captcha

def check_image_captcha():
    if ans.get() == get_image():
        tkinter.messagebox.showinfo("Success!","CAPTCHA code Matched.")
        tkinter.messagebox.showinfo("Wrong!","CAPTCHA code does not Match.")

This is the regenerate function

This the image before clicking on the regenerate button
def regenerate_image_captcha():
global isClicked
isClicked = True

    img = ImageCaptcha()

    s = generate_captcha()

    value = img.generate(s)

root = Tk()
root.title("GUI : CAPTCHA Generation")

root.configure(background = '#ffd9db')
Tops = Frame(pady = 1, width = 550, height = 50, relief = "ridge", background = '#ffd9db')
Tops.grid(row = 0, column = 0)

ans = StringVar()


# MainFrame = Frame(root, pady = 2, width = 1350, height = 100, relief = "ridge", background = '#ffd9db')

# MainFrame.grid(row = 1, column = 0)

Label_Heading = Label(font = ('lato black', 15, 'bold',), text = "Verify Captcha", background = '#ffd9db')
Label_Heading.grid(row = 1, column = 0)


#Label_show = Button(font = ('arial', 20, 'bold'), text = "Show", padx = 2, pady = 2, bg = "white", command = generate_image_captcha)
#Label_show.grid(row = 2, column = 0)

img = cv2.imread('cap.png')
im = Image.fromarray(img)

imgtk = ImageTk.PhotoImage(image = im)

tkinter.Label(root, image = imgtk).grid(row = 2, column = 0)

Enter_captcha = Entry(font = ('arial', 20, 'bold'), bd = 2, fg = "black", textvariable = ans, width = 14).grid(row = 3, column = 0)

Label_Check_Captcha = Button(font = ('arial', 20, 'bold'), text = "Check", padx = 2, pady = 2, bg = "white", command = check_image_captcha)
Label_Check_Captcha.grid(row = 4, column = 0)

regenerate button I
Label_regenerate_Captcha = Button(font = (‘arial’, 20, ‘bold’), text = “Regenerate”, padx = 2, pady = 2, bg = “white”, command = regenerate_image_captcha)
Label_regenerate_Captcha.grid(row = 5, column = 0)

if Label_regenerate_Captcha == True:
    img = cv2.imread('cap.png')
    im = Image.fromarray(img)

    imgtk = ImageTk.PhotoImage(image = im)

    tkinter.Label(root, image = imgtk).grid(row = 6, column = 0)


How can I copy the quality (illumination, contrast, brightness, etc) from one picture to another on OPENCV?

I have two images and I want to use the 2nd image as a basis to edit the quality of the 1st image.

How can I do this on openCV?

1st Image

2nd Image