0

I am new to working on image processing. I have a folder that has images of various cars. I am trying to extract only their nameplates and put it in a different folder. I am getting an error stating "ValueError: too many values to unpack (expected 2)" in line 5 of the below code. I looked up for this code on the internet and trying to understand it. As far as I could figure out, we are first using the imread function to read the image and converting it into gray color space. The Canny function helps detect edges and findContours helps find the contours of the image. I don't seem to understand the code further ahead. It will be helpful if someone could guide me through the code as well as help me sort the error.

import cv2 
image = cv2.imread("path")
imgray = cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
ret,thresh = cv2.threshold(imgray,127,255,0)
im2, contours, hierarchy = 
cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
cnt = contours[4]
cv2.drawContours(im2, [cnt], 0, (0,255,0), 3)
idx = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    if w>50 and h>50:
        idx+=1
        new_img=image[y:y+h,x:x+w]
        cv2.imwrite(str(idx) + '.png', new_img)
cv2.imshow("im",image)
cv2.waitKey(0)
SSV
  • 149
  • 2
  • 12
  • @chitown88 thanks for the reply. it was just some editing problem. fixed it – SSV Dec 14 '18 at 14:27
  • @chitown88, seems to work fine for me – SSV Dec 14 '18 at 14:30
  • 1
    I guess you're using OpenCV 3.x, and reading documentation or tutorial written for 2.x -- the API changed and `findContours` in 3.x returns 3 values instead of two. Another sign is that you give it a copy of the input image (in 2.x it modified the input). – Dan Mašek Dec 14 '18 at 14:36
  • looking into it, it seems to have changed with cv 3.0. I think I found it, so testing now and will post back to you – chitown88 Dec 14 '18 at 14:37
  • @DanMašek Yes thank you so much. I got it. – SSV Dec 14 '18 at 14:41
  • @chitown88 , thanks but unable to get the nameplate of the car – SSV Dec 14 '18 at 15:03

2 Answers2

1

There was a change in cv 3.0 Has to do with .findContours returns 3 values now.

https://docs.opencv.org/3.1.0/d4/d73/tutorial_py_contours_begin.html

import cv2 
image = cv2.imread("path")
gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY)
edged = cv2.Canny(image, 10, 250)

#old way
#(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 3.0 way
_, cnts, hierarchy = cv2.findContours(edged, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

idx = 0
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    if w>50 and h>50:
        idx+=1
        new_img=image[y:y+h,x:x+w]
        cv2.imwrite(str(idx) + '.png', new_img)
cv2.imshow("im",image)
cv2.waitKey(0)
chitown88
  • 27,527
  • 4
  • 30
  • 59
0
im2, contours, hierarchy = 
cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
SSV
  • 149
  • 2
  • 12