using OpenCV to find the seletected ball's center in python [closed]

asked 2016-07-27 04:14:06 -0600

Zero.J gravatar image

Hi everyone,

I'm a beginner and trying to use the basic OpenCV to find the choose color ball's center x,y value from the image. But When I try to run my program there had some error happen but I had no idea what's wrong in my program. Can anyone help me?

Follow is my progam:

#!/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,86,6)
        upper = (64,255,255)

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

    print color

    image_hsv = cv2.cvtColor(image_src,cv2.COLOR_BGR2HSV)##################
    image_mask = cv2.inRange(image_hsv,lower,upper)

    image_mask = cv2.erode(image_mask, None, iterations=2)
    image_mask = cv2.dilate(image_mask, None, iterations=2)

    print ("end maskingg")

    print ("finding center.........")

    contours,hierarchy = cv2.findContours(image_mask,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)[-2]

    if len(contours) > 0:

        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_src, (int(x), int(y)), int(radius),(0, 255, 255), 2)

            cv2.circle(image_src, center, 2, (0, 0, 255), -1)

def main():
    global ball_color
    global image_src

    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/ColorBalls.jpg',1)

    image_processing(args.color)

    cv2.imshow("image_processed",image_src)

if __name__=='__main__':
    main()

This is the error message show:

Initializing...........................................
deciding color...............
blue
OpenCV Error: Assertion failed ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F)) in cvtColor, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp, line 3959
Traceback (most recent call last):
  File "/home/leddar/ros_ws/src/baxter_examples/scripts/ylj/ylj_imgball.py", line 101, in <module>
    main()
  File "/home/leddar/ros_ws/src/baxter_examples/scripts/ylj/ylj_imgball.py", line 91, in main
    image_processing(args.color)
  File "/home/leddar/ros_ws/src/baxter_examples/scripts/ylj/ylj_imgball.py", line 36, in image_processing
    image_hsv = cv2.cvtColor(image_src,cv2.COLOR_BGR2HSV)##################
cv2.error: /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp:3959: error: (-215) (scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F) in function cvtColor
edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by berak
close date 2016-07-27 05:11:35.039134

Comments

1

error means, that the input to cvtColor was invalid. your image probably was not read.

add some print checks after imread() (and please use less global vars !)

berak gravatar imageberak ( 2016-07-27 04:17:33 -0600 )edit

So what kind of print checks should I use? I kind of new in OpenCV would you mind give more detail things?Thank you

Zero.J gravatar imageZero.J ( 2016-07-27 04:19:45 -0600 )edit

I try add the :

print ("Initializing...........................................")
    rospy.init_node("ylj_ballposition",anonymous=True)
    image_src = cv2.imread('home/ros_ws/src/baxter_examples/ColorBalls.jpg')
    **print ("read the image....")**

Then will shows:

   Initializing...........................................
        read the image....
        deciding color...............
        blue
        OpenCV Error: Assertion failed ((scn == 3 || scn == 4) && (depth == CV_8U || depth == CV_32F)) in cvtColor, file /build/buildd/opencv-2.4.8+dfsg1/modules/imgproc/src/color.cpp, line 3959
        Traceback (most recent call last):

The rest of error message still same.

Zero.J gravatar imageZero.J ( 2016-07-27 04:23:34 -0600 )edit
1

since the imread() output is a numpy array, check for None or np.shape(img)==()

berak gravatar imageberak ( 2016-07-27 04:24:23 -0600 )edit

Sorry....I had no idea about how to check the None or np.shape(img)==(). Would you mind teach me how to check it? or any website can find it?

Zero.J gravatar imageZero.J ( 2016-07-27 04:33:22 -0600 )edit

cmon, that's just plain python..

if src_image == None:
     print "§$§R$§R§§"
berak gravatar imageberak ( 2016-07-27 04:35:52 -0600 )edit
1

oh, I found the method. It's just if image_src is None:

print ("the image read is None............")

And the showing result shows that it is None. It's that mean I didn't read the image?

Zero.J gravatar imageZero.J ( 2016-07-27 04:37:07 -0600 )edit

hey, exactly ;)

now check, if there's really something in 'home/ros_ws/src/baxter_examples/ColorBalls.jpg' , and, shouldn't it be: '/home/ros_ws/src/baxter_examples/ColorBalls.jpg' ? (imho, you need to add a slash at the beginning, to make it an correct absolute path)

berak gravatar imageberak ( 2016-07-27 04:49:13 -0600 )edit
1

Hi berak, I follow you idea and change the image reading path, then my problem was solved. Thank you for your advice.

Zero.J gravatar imageZero.J ( 2016-07-27 04:51:13 -0600 )edit