#!/usr/bin/env python
from __future__ import print_function

import roslib
import sys
import rospy
import cv2
import numpy as np
import matplotlib.pyplot as plt
from std_msgs.msg import String
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError

class image_converter:

  def __init__(self):
    self.image_pub = rospy.Publisher("/myresult", Image, queue_size=2)

    self.bridge = CvBridge()
    self.image_sub = rospy.Subscriber("/cf1/camera/image_raw", Image, self.callback)

  def callback(self,data):
    # Convert the image from OpenCV to ROS format
    try:
      cv_image = self.bridge.imgmsg_to_cv2(data, "bgr8")
    except CvBridgeError as e:
      print(e)

    # Convert BGR to HSV
    hsv = cv2.cvtColor(cv_image, cv2.COLOR_BGR2HSV)


    # True HSV for red in stop sign 
    H = int(357/2)-1
    S = int(0.826*255)
    V = int(0.698*255)

    #  lowerRed: 50,180,0
    #  upperRed: 180,270,180

    # define range of the color we look for in the HSV space
    whiteLower = np.array([0,0,250])
    whiteUpper = np.array([255,5,255])

    redLower = np.array([H-5,S-8,V-5])
    redUpper = np.array([H+5,S+8,V+5])


    # Threshold the HSV image to get only the pixels in ranage
    maskWhite = cv2.inRange(hsv, whiteLower, whiteUpper)
    maskRed = cv2.inRange(hsv,redLower,redUpper)

    # Find center of stop sign 
    position = np.where(maskRed==np.amax(maskRed))
    x = np.mean(position[0][:])
    y = np.mean(position[1][:])


    # Create mask for both red and white
    stopSignMask = cv2.bitwise_or(maskRed,maskWhite)

    # Bitwise-AND mask and original image
    res = cv2.bitwise_and(cv_image, cv_image, mask= stopSignMask)

    #(rows,cols,channels) = res.shape
    nRed = np.count_nonzero(maskRed)
    nWhite = np.count_nonzero(maskWhite)

    # print('red')
    # print(nRed)
    # print(nRed)
    # print('white')
    # print(nWhite)
    # print('x=',x)
    # print('y=',y)

    if nRed > 550 and nWhite > 90:
      rospy.loginfo('Stopsign detected')
      cv2.circle(res, (int(y),int(x)), 50, 255)
    # Assuming it is larger than 100x100 we draw a 100x100 circle at 50,50 with radius 50 into the image


    # Publish the image
    try:
      self.image_pub.publish(self.bridge.cv2_to_imgmsg(res, "bgr8"))
    except CvBridgeError as e:
      print(e)

def main(args):
  rospy.init_node('colorseg', anonymous=True)

  ic = image_converter()

  print("running...")
  try:
    rospy.spin()
  except KeyboardInterrupt:
    print("Shutting down")

  cv2.destroyAllWindows()

if __name__ == '__main__':
    main(sys.argv)