How can I select the good colors from an image with OpenCV and mask?

前端 未结 1 1497
萌比男神i
萌比男神i 2020-12-19 18:37

I\'m trying to select a color in an picture. I\'m using OpenCV to do so and I\'m learning from the page https://realpython.com/python-opencv-color-spaces/ . The image I\'m t

相关标签:
1条回答
  • 2020-12-19 18:58

    Your color ranges are not quite right yet. Also the variables in the inRange() function are in the wrong order. It's from-to, so the darker color must be first. Change your code to cv2.inRange(hsv_nucl, green2hsv,greenhsv) You can use/tweak the values in the code below, that works.
    Result:

    With white background:

    import numpy as np 
    import cv2
    
    # load image
    img = cv2.imread("Eding.png")
    # convert to HSV
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) 
    # set lower and upper color limits
    lower_val = np.array([50,100,170])
    upper_val = np.array([70,255,255])
    # Threshold the HSV image to get only green colors
    mask = cv2.inRange(hsv, lower_val, upper_val)
    # apply mask to original image - this shows the green with black blackground
    only_green = cv2.bitwise_and(img,img, mask= mask)
    
    # create a black image with the dimensions of the input image
    background = np.zeros(img.shape, img.dtype)
    # invert to create a white image
    background = cv2.bitwise_not(background)
    # invert the mask that blocks everything except green -
    # so now it only blocks the green area's
    mask_inv = cv2.bitwise_not(mask)
    # apply the inverted mask to the white image,
    # so it now has black where the original image had green
    masked_bg = cv2.bitwise_and(background,background, mask= mask_inv)
    # add the 2 images together. It adds all the pixel values, 
    # so the result is white background and the the green from the first image
    final = cv2.add(only_green, masked_bg)
    
    #show image
    cv2.imshow("img", final)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    
    0 讨论(0)
提交回复
热议问题