Ask Your Question
0

had problem when convert the image from BGR to HSV

asked 2016-07-28 00:05:21 -0600

Zero.J gravatar image

updated 2016-07-28 00:17:51 -0600

Hi everyone,

I'm just a beginner in OpenCV. I'm trying to find the green ball's center point in the image. But when I try to convert the image from BGR to HSV the shows image result will be change to another kind of color instead of the orignal image. This is the result image after the convertion: image description

image description

Base on my simple understand it should not show this image results after the BGR to HSV. So does anyone know what's the problem cause my problem? Thank you!

Follow is my whole program:

#!/usr/bin/env python
# coding=utf-8

import sys
import rospy
import cv2
#import cv
import argparse
import numpy as np
from std_msgs.msg import String
from sensor_msgs.msg import Image
import std_srvs.srv


def image_processing (color):
    #image_src = cv2.imread('home/ros_ws/src/baxter_examples/ColorBalls.jpg',0)

    print ("deciding color...............")
    if color == "blue":
        lower = (86,31,4)
        upper = (220,88,50)

    if color == "green":
        lower = (29,30,20)
        upper = (64,255,255)

    if color == "red":
        lower = (17,15,100)
        upper = (50,56,200)

    print color

    image_hsv = cv2.cvtColor(image_resized,cv2.COLOR_BGR2HSV)
    cv2.imshow("or_image",image_hsv)
    cv2.waitKey(0)
    cv2.destroyAllWindows()
    image_mask = cv2.inRange(image_hsv,lower,upper)
    #cv2.imshow("or_image",image_mask)
    #cv2.waitKey(0)

    image_mask = cv2.erode(image_mask, None, iterations=2)
    image_mask = cv2.dilate(image_mask, None, iterations=2)
    cv2.imshow("or_image",image_mask)
    cv2.waitKey(0)

    print ("end maskingg")
    print ("finding center.........")

    contours, hierarchy = cv2.findContours(image_mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
    if contours  is None:
        print ("cont is None")
    print ("len.........")
    print  len(contours)

    if len(contours) > 0:
        print  ("############################")
        print  len(contours)

        c =  max (contours,key=cv2.contourArea)
        ((x, y), radius) = cv2.minEnclosingCircle(c)
        M = cv2.moments(c)
        center = (int(M["m10"] / M["m00"]), int(M["m01"] / M["m00"]))

        print center

        if radius > 1:
            cv2.circle(image_resized, (int(x), int(y)), int(radius),(0, 255, 255), 2)
            cv2.circle(image_resized, center, 2, (0, 0, 255), -1)

def main():
    global ball_color
    global image_src
    global image_resized

    arg_fmt = argparse.RawDescriptionHelpFormatter
    parser = argparse.ArgumentParser(formatter_class=arg_fmt, description=main.__doc__)

    parser.add_argument(
        '-c','---color', dest='color',choices=['blue','green','red'], required=True,
        help= "the ball color to pick up", 
         )
    args=parser.parse_args()

    print ("Initializing...........................................")
    rospy.init_node("ylj_ballposition",anonymous=True)

    #image_src = cv2.imread('/home/ros_ws/src/baxter_examples/scripts/ColorBalls.JPG')
    print ("reading the image")
    image_src = cv2.imread('Balls.JPG')
    print ("readed..............")

    if image_src is None:
        print ("the image read is None............")

    #print ("show the image............")
    #cv2.imshow("or_image",image_src)
    #cv2.waitKey(0)

    print image_src.shape
    print ("resizing........")
    image_resized = cv2.resize(image_src,(400,300),interpolation = cv2.INTER_AREA)
    print image_resized.shape
    print ("resized........")

    #cv2.imshow("or_image",image_resized)
    #cv2.waitKey(0)

    print ("start image processing......")
    image_processing(args.color)

    cv2.imshow("image_processed",image_resized)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__=='__main__':
    main()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted
1

answered 2016-07-28 00:14:18 -0600

berak gravatar image

updated 2016-07-28 01:10:12 -0600

there is no problem at all, HSV, LAB or YUV images just "look weird" ;) (this is the expected result !)

what you're seing there is: H in the blue channel, S in the green channel, V in the red one (the HSV channels are linearly mapped to a BGR one for visualization)

[edit:]

maybe it gets easier, if you can just "click" your object, to determine the center color for your range ?

have a look at the python gui tutorials

import cv2
import numpy as np

image_hsv = None   # global ;(
pixel = (20,60,80) # some stupid default

# mouse callback function
def pick_color(event,x,y,flags,param):
    if event == cv2.EVENT_LBUTTONDOWN:
        pixel = image_hsv[y,x] # check pixel under mouse
        print pixel

        # you might want to adjust the ranges(+-10, etc):
        upper = (pixel[0] + 10, pixel[1] + 10, pixel[2] + 40)
        lower = (pixel[0] - 10, pixel[1] - 10, pixel[2] - 40)

        image_mask = cv2.inRange(image_hsv,lower,upper)
        cv2.imshow("mask",image_mask)

def main():
    global image_hsv, pixel # so we can use it in mouse callback

    image_src = cv2.imread('balls.png')
    if image_src is None:
        print ("the image read is None............")
        return
    cv2.imshow("bgr",image_src)

    ## NEW ##
    cv2.namedWindow('hsv')
    cv2.setMouseCallback('hsv', pick_color)

    # now click into the hsv img , and look at values:
    image_hsv = cv2.cvtColor(image_src, cv2.COLOR_BGR2HSV)
    cv2.imshow("hsv", image_hsv)

    cv2.waitKey(0)
    cv2.destroyAllWindows()

if __name__=='__main__':
    main()

scrot

edit flag offensive delete link more

Comments

1

Hi berak, So which is mean that my converting part was no problem right?

Zero.J gravatar imageZero.J ( 2016-07-28 00:16:50 -0600 )edit

no problem, everything's fine !

(and you'll get used to the weird look soon ;)

berak gravatar imageberak ( 2016-07-28 00:22:26 -0600 )edit

Haha, ok. Thank you! And one more question, since my converting was correct. But when I try to do the cv2.inRange, I cannot do the mask very well. due to the lower and upper value was not set so good. So do you know any way can find out the Blue, Green or Red color's range?

Zero.J gravatar imageZero.J ( 2016-07-28 00:27:08 -0600 )edit

see edit ;)

berak gravatar imageberak ( 2016-07-28 01:11:23 -0600 )edit

wow! cool! Let me try it. So the edited part just need simply add into my program or I have to write a new program to do?

Zero.J gravatar imageZero.J ( 2016-07-28 01:20:28 -0600 )edit
1

probably easier to start with a new file. play with it, adapt. (and dig the tutorials !)

berak gravatar imageberak ( 2016-07-28 01:23:33 -0600 )edit

ok, thank you so much.

Zero.J gravatar imageZero.J ( 2016-07-28 01:28:16 -0600 )edit

Hi berak,

Thank you so much! Your idea is totally work for me!

Zero.J gravatar imageZero.J ( 2016-07-28 05:48:39 -0600 )edit

Question Tools

1 follower

Stats

Asked: 2016-07-28 00:05:21 -0600

Seen: 3,235 times

Last updated: Jul 28 '16