0

I have the following error...

error

The code of which is referred is the this:

from hog import HOG
import dataset
import argparse
import _pickle as cPickle
import mahotas
import cv2


ap = argparse.ArgumentParser()
ap.add_argument("-m", "--model", required = True,
    help = "path to where the model will be stored")
ap.add_argument("-i", "--image", required = True,
    help = "path to the image file")
args = vars(ap.parse_args())

model = open(args["model"]).read()
model = cPickle.loads(model)

hog = HOG(orientations = 18, pixelsPerCell = (10, 10),
cellsPerBlock = (1, 1), normalize = True)

image = cv2.imread(args["image"])
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edged = cv2.Canny(blurred, 30, 150)
(cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

cnts = sorted([(c, cv2.boundingRect(c)[0]) for c in cnts], key =lambda x: x[1])

for (c, _) in cnts:
    (x, y, w, h) = cv2.boundingRect(c)
    if w >= 7 and h >= 20:
        roi = gray[y:y + h, x:x + w]
        thresh = roi.copy()
        T = mahotas.thresholding.otsu(roi)
        thresh[thresh > T] = 255
        thresh = cv2.bitwise_not(thresh)
        thresh = dataset.deskew(thresh, 20)
        thresh = dataset.center_extent(thresh, (20, 20))
        cv2.imshow("thresh", thresh)

        hist = hog.describe(thresh)
        digit = model.predict(hist)[0]
        print
        "I think that number is: %d" % (digit)
        cv2.rectangle(image, (x, y), (x + w, y + h),
            (0, 255, 0), 1)
        cv2.putText(image, str(digit), (x - 10, y - 10),
            cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 255, 0), 2)
        cv2.imshow("image", image)
        cv2.waitKey(0)

This one is "linked" to another part (another .py file in the same package...), which is this:

from sklearn.svm import LinearSVC
from hog import HOG
import dataset
import argparse
import _pickle as cPickle


ap = argparse.ArgumentParser()
ap.add_argument("-d", "--dataset", required = True,
    help = "path to the dataset file")
ap.add_argument("-m", "--model", required = True,
    help = "path to where the model will be stored")
args = vars(ap.parse_args())

(digits, target) = dataset.load_digits(args["dataset"])
data = []

hog = HOG(orientations = 18, pixelsPerCell = (10, 10),
    cellsPerBlock = (1, 1), normalize = True)

for image in digits:
    image = dataset.deskew(image, 20)
    image = dataset.center_extent(image, (20, 20))

    hist = hog.describe(image)
    data.append(hist)

model = LinearSVC(random_state = 42)
model.fit(data, target)
f = open(args["model"], "w")
f.write(str(cPickle.dumps(model)))
f.close()

NOTE: In this line ---> f.write(str(cPickle.dumps(model))) I casted it by myself to str because it was giving error when I had tried to execute this last one block.

By the way, someone knows why it gives the error showed in CMD ?

Thanks

lucians
  • 2,239
  • 5
  • 36
  • 64
  • `cPickle` has a `dump` function, where you pass a file opened in binary mode. Use that directly. – cs95 Aug 03 '17 at 18:53
  • edited answer. I am using cPickle for the first time right now... – lucians Aug 03 '17 at 18:57
  • Marked duplicate based on your "edit". – cs95 Aug 03 '17 at 19:02
  • was reading that.. – lucians Aug 03 '17 at 19:03
  • We generally discourage users editing their questions to oblivion as it is not useful to future readers. One question should typically address one issue, and you should open a new question if you have an unrelated problem. – cs95 Aug 03 '17 at 19:04
  • You're right....Now should I edit or leave it as is ? – lucians Aug 03 '17 at 19:05
  • 1
    Here's what I recommend. 1. Rollback your edit. 2. Accept one of these answers as they helped. 3. Do a little research, look for a solution. If nothing works, open a new question. :) – cs95 Aug 03 '17 at 19:07

2 Answers2

1

Try opening your file in bytes mode. So replace

f = open(args["model"], "w")

with

f = open(args["model"], "wb")
MLavrentyev
  • 1,827
  • 2
  • 24
  • 32
  • Did like you said. Deleted str() casting. The main code seems to work. But now I have another error...Update answer.. – lucians Aug 03 '17 at 18:51
  • Is this: https://stackoverflow.com/questions/9233027/unicodedecodeerror-charmap-codec-cant-decode-byte-x-in-position-y-character But I don't know how to apply the solution to my code.. – lucians Aug 03 '17 at 19:11
  • By the way, I added 'wb' to either two file (code 1 and code 2). Executing the firs one, I have this other error: `Traceback (most recent call last): File "classify.py", line 16, in model = open(args["model"], 'wb').read() io.UnsupportedOperation: read` – lucians Aug 03 '17 at 19:17
1

You need to write and read your pickle as bytes, not text:

# Reading
with open(args['model'], 'b') as f:
    model = cPickle.load(f)

...

# Writing
with open(args['model'], 'wb') as f:
    cPickle.dump(model, f, 2)
user2357112
  • 260,549
  • 28
  • 431
  • 505